Exclude columns getting data with Entity Framework [duplicate]

空扰寡人 提交于 2020-01-16 18:16:06

问题


I'm using Entity Framework in C#. And I want exclude some columns while getting data from database. For example, my student table has 10 colums. And there is some columns in table like CreatedDate, CreatedBy, CreateRole, UpdatedDate, Updatedby, UpdatedRole. I want generic solution for exclude this column while getting list from database like below.

I'm looking for like below

 context.Students   
.Exclude("CreatedDate","CreatedBy","CreateRole","UpdatedDate","Updatedby","UpdatedRole")
.ToList();

Please don't advice below solution, because this is not what I'm looking for.

context.Students.Select(p=>new {
p.Name,
p.Surname,
p.Number,
p.BirthDate
}).ToList();

回答1:


As stated in my comments, I would create a model, for the properties which are only needed occasionally:

public class CreateAndUpdatePropertiesModel
{
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public DateTme ModifiedDate { get; set; }
    public string ModifiedBy { get; set; }
    // ...and so on
}

And then use this model as a property in my primary model:

public class StudentModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    // ...rest of the properties here

    // And then add the CreateAndUpdateProperties model as a property
    public CreateAndUpdateProperties { get; set; }
}

Then when you select items from Entity Framework, you can use

.Include(s => s.CreateAndUpdateProperties)

if you want to include the create and update properties. Without this include, it would just be null.




回答2:


You can modify DBContext as follows.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Students>().Ignore(t=>t.CreatedDate).Ignore(t=>t.CreatedBy).Ignore(t=>t.CreateRole).Ignore(t=>t.UpdatedDate).Ignore(t=>t.Updatedby).Ignore(t=>t.UpdatedRole);

    base.OnModelCreating(modelBuilder);
}


来源:https://stackoverflow.com/questions/53553305/exclude-columns-getting-data-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!