How to select just some fields from a table in EF

前端 未结 2 547
孤街浪徒
孤街浪徒 2021-02-02 15:59

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

2条回答
  •  心在旅途
    2021-02-02 16:22

    There can be many ways to do this job, but using Automapper NuGet package is the most simple one I have experienced.

    • First: Install Autmapper NuGet package for your project from NuGet package explorer.
    • Second: Make a simple ViewModel, which contains only required attributes:

      public class UserViewModel {
          public int ID {get; set;}
          public string FirstName {get; set;}
          public string LastName {get; set;}
      }
      
    • Third: Initialize your your mapper only for once in app_start class like:

      namespace SampleProject.App_Start {
          public class AutoMapperConfig {
              public static void Initializer() {
                  AutoMapper.Mapper.Initialize(cfg => {
      
                      cfg.CreateMap()
                  });
               }
           }
      }
      
    • Fourth: Add it's entry in Global.asax.cs:

      namespace SampleProject
      {
          public class MvcApplication : System.Web.HttpApplication
          {
              protected void Application_Start()
              {
                  AreaRegistration.RegisterAllAreas();
                  GlobalConfiguration.Configure(WebApiConfig.Register);
                  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                  RouteConfig.RegisterRoutes(RouteTable.Routes);
                  BundleConfig.RegisterBundles(BundleTable.Bundles);
      
                  // AutoMapper Initializer
                  App_Start.AutoMapperConfig.Initializer();
              }
          }
      }
      
    • Fifth: Use it in your controller where you want like this:

      namespace SampleProject.Controllers
      {
          public class UsersController : Controller
          {
              private DataContext db = new DataContext();
      
              public ActionResult Index()(
                  var model = AutoMapper.Mapper.Map>(db.User.ToList());
                  return View(model);
      
              }
          }
      }
      
    • Last: You can create as many maps as you want between your Models and ViewModels by initializing them once in the app_start's AutoMapperConfig 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 on MVC 3 or older than MVC 5.

提交回复
热议问题