如何选择刚刚从EF表中的某些字段 [英] How to select just some fields from a table in EF

查看:190
本文介绍了如何选择刚刚从EF表中的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库9列的表,我希望能够加载只有它的某些领域,如果我需要。

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.

我怎样才能做到这一点与实体框架4好吗?

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

我的项目是一个 ASP.NET MVC 3 应用程序,其中的SQLServer 2008年防爆preSS EF 4.1

推荐答案

假设你有这种模式的表格:

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;}
}

现在,你要取只是 ID FotherName 。你可以做到这一点在2路;第一种方式是获取它们作为一个匿名对象,看看:

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 anonymous object, look:

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:

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

在另一种方式(例如,当您想要的通过的对象为型号查看),你可以定义一个新的类(即 UserViewModel ),当您选择的对象,选择它作为一个 UserViewModel 。看:

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 a UserViewModel. look:

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;}
}

和查询,借此:

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();

看刚 ONE 的区别是它们之间,在labda前pression,而不是 U =>新{}
我们使用 U =>新UserViewModel {} 。祝你好运。

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

这篇关于如何选择刚刚从EF表中的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆