I have a table with 9 columns in database and I want to be able to load only some fields of it if I need.
How can I do this with Entity Framework 4 please?
e.g. My table has these fields:
ID, FirstName, LastName, FotherName, BirthDate, Mobile, Email
and I want to be able to fetch just these columns:
ID, FirstName, LastName
My project is an ASP.NET MVC 3 application, with SQLServer 2008 Express and EF 4.1.
Assume you have a table with this model:
Now, you want fetch just
ID,FirstName,LastName, andFotherName. You can do it in 2 way; The first way is fetch them as ananonymousobject, look:Now, your return-value-type is
anonymous, you can work with it such as:In another way (for example when you want to pass the object as an Model to a View), you can define a new class, (i.e.
UserViewModel), and when you select the object, select it as aUserViewModel. look:and in query, take this:
Look that just ONE difference is between them, in labda expression, instead of
u => new {}we are using
u => new UserViewModel{}. Good luck.