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 ananonymous
object, 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 usingu => new UserViewModel{}
. Good luck.There can be many ways to do this job, but using
Automapper
NuGet package is the most simple one I have experienced.Autmapper
NuGet package for your project from NuGet package explorer.Second: Make a simple
ViewModel
, which contains only required attributes:Third: Initialize your your mapper only for once in
app_start
class like:Fourth: Add it's entry in
Global.asax.cs
:Fifth: Use it in your controller where you want like this:
Last: You can create as many maps as you want between your
Models
andViewModels
by initializing them once in theapp_start
'sAutoMapperConfig
class and use them where you want with a simple line of code.Also you can find a lot of help about
Automapper
if you search about it. Its main website is here.Important:
I am a developer of
ASP.NET MVC 5
.Automapper
works fine for me every time. I cannot check it onMVC 3
or older thanMVC 5
.