How to select just some fields from a table in EF

前端 未结 2 538
孤街浪徒
孤街浪徒 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:20

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

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

    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 ONE difference is between them, in labda expression, instead of u => new {} we are using u => new UserViewModel{}. Good luck.

提交回复
热议问题