asp.net-mvc 如何从 EF 的表中只选择一些字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7356180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:27:58  来源:igfitidea点击:

How to select just some fields from a table in EF

asp.net-mvcentity-frameworkasp.net-mvc-3lambdaentity-framework-4.1

提问by ravy amiry

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.

我在数据库中有一个包含 9 列的表,如果需要,我希望能够仅加载其中的某些字段。

How can I do this with Entity Framework 4 please?

请问如何使用 Entity Framework 4 做到这一点?

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 3application, with SQLServer 2008 Expressand EF 4.1.

我的项目是一个ASP.NET MVC 3应用程序,带有SQLServer 2008 ExpressEF 4.1

回答by ravy amiry

Assume you have a table with this model:

假设您有一个具有此模型的表:

public class User{
    public int ID {get; set;}
    public string NickName {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string FotherName {get; set;}
    public DateTime BirthDate {get; set;}
    public string Mobile {get; set;}
    public string Email {get; set;}
    public string Password {get; set;}
}

Now, you want fetch just ID, FirstName, LastName, and FotherName. You can do it in 2 way; The first way is fetch them as an anonymousobject, look:

现在,你要取刚IDFirstNameLastName,和FotherName。您可以通过 2 种方式进行操作;第一种方法是将它们作为一个anonymous对象来获取,看看:

var user = entityContext.Users.Where(u => u.ID == id)
    .Select(u => new {
        ID = u.ID,
        FirstName = u.FirstName,
        LastName = u.LastName,
        FotherName = u.FotherName
    }).Single();

Now, your return-value-type is anonymous, you can work with it such as:

现在,您的返回值类型是anonymous,您可以使用它,例如:

var i = user.ID;
// or
var s = user.FirstName;

In another way (for example when you want to passthe object as an Modelto a View), you can define a new class, (i.e. UserViewModel), and when you select the object, select it as a UserViewModel. look:

以另一种方式(例如,当你想传递的对象作为模型视图),可以定义一个新的类,(即UserViewModel),当您选择的对象,选择它作为一个UserViewModel。看:

public class UserViewModel{
    public int ID {get; set;}
    public string NickName {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string FotherName {get; set;}
}

and in query, take this:

并在查询中,采取这个:

var user = entityContext.Users.Where(u => u.ID == id)
    .Select(u => new UserViewModel {
        ID = u.ID,
        FirstName = u.FirstName,
        LastName = u.LastName,
        FotherName = u.FotherName
    }).Single();

Look that just ONEdifference is between them, in labda expression, instead of u => new {}we are using u => new UserViewModel{}. Good luck.

看看它们之间只有一个区别,在labda 表达式中,而不是u => new {}我们使用u => new UserViewModel{}. 祝你好运。

回答by Rahmat Ali

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

有很多方法可以完成这项工作,但使用AutomapperNuGet 包是我体验过的最简单的一种。

  • First: Install AutmapperNuGet 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_startclass like:

    namespace SampleProject.App_Start {
        public class AutoMapperConfig {
            public static void Initializer() {
                AutoMapper.Mapper.Initialize(cfg => {
    
                    cfg.CreateMap<User, UserViewModel>()
                });
             }
         }
    }
    
  • 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<List<UserViewModel>>(db.User.ToList());
                return View(model);
    
            }
        }
    }
    
  • Last: You can create as many maps as you want between your Modelsand ViewModelsby initializing them once in the app_start's AutoMapperConfigclass and use them where you want with a simple line of code.

  • 首先Autmapper从 NuGet 包资源管理器为您的项目安装NuGet 包。
  • 第二:做一个简单的ViewModel,只包含必需的属性:

    public class UserViewModel {
        public int ID {get; set;}
        public string FirstName {get; set;}
        public string LastName {get; set;}
    }
    
  • 第三:在app_start课堂上只初始化一次你的映射器,比如:

    namespace SampleProject.App_Start {
        public class AutoMapperConfig {
            public static void Initializer() {
                AutoMapper.Mapper.Initialize(cfg => {
    
                    cfg.CreateMap<User, UserViewModel>()
                });
             }
         }
    }
    
  • 第四:添加它的条目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();
            }
        }
    }
    
  • 第五:在您想要的控制器中使用它,如下所示:

    namespace SampleProject.Controllers
    {
        public class UsersController : Controller
        {
            private DataContext db = new DataContext();
    
            public ActionResult Index()(
                var model = AutoMapper.Mapper.Map<List<UserViewModel>>(db.User.ToList());
                return View(model);
    
            }
        }
    }
    
  • 最后:您可以在Models和之间创建任意数量的映射,方法ViewModels是在app_start'sAutoMapperConfig类中初始化它们,并通过简单的一行代码在需要的地方使用它们。

Also you can find a lot of help about Automapperif you search about it. Its main website is here.

Automapper如果你搜索它,你也可以找到很多帮助。它的主要网站在这里







Important:

重要的:

I am a developer of ASP.NET MVC 5. Automapperworks fine for me every time. I cannot check it on MVC 3or older than MVC 5.

我是ASP.NET MVC 5. Automapper每次都对我有用。我无法在MVC 3或 之前检查它MVC 5