1

Possible Duplicate:
Retrieve an object from entityframework without ONE field

I am working on asp.net mvc. currently i am using EF 4.1 code first model. Here i have list of records(43). My class is like,

public class MyTable
{
public string field1{get; set;}
public string field2{get; set;}
.
.
.
public string field20{get; set;}
} 

and i am returning them as a list like List. But i dont want the field20 to return. so how could i skip particular field in my list. I have used like,

(from m in context.MyTable select new{m.field1,m.field2,...,m.field19}).ToList(); 

Its working very fine. but i want same result using lambda expression syntax like

context.MyTable.Skip() or any etc.

How to return only particular fields to list.

Community
  • 1
  • 1
Karthik Bammidi
  • 1,851
  • 9
  • 31
  • 65

1 Answers1

1

well you can write

context.MyTable.Select(x => new { x.field1, x.field2, ..., x.field19}).ToList();

If you don't want to write all 19 fields, you can make you MyTable class implement IEnumerable

public class MyTable : IEnumerable<object>

public IEnumerator<object> GetEnumerator()
{
    List<object> list = new List<object>();
    list.Add(field1);
    list.Add(field2);
    ...
    list.Add(field20);
    return list.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

And then you can write

context.MyTable.Select(x => x.Take(19).ToList()).ToList();
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • Thanks for your reply. i know the method you answered i need to write 19 properties is there any way to skip single column. – Karthik Bammidi Oct 27 '12 at 12:59
  • I think it's possible only by two ways - through reflection and if your MyTable will implement IEnumerable. I've changed an answer, may be it will help. – Roman Pekar Oct 27 '12 at 13:17
  • This solution is very useful when one of the fields in the database is a byte[ ], skipping this when iterating through this table is much, much faster. – TK-421 Jun 02 '20 at 10:33