首页 > 解决方案 > 排除使用实体框架获取数据的列

问题描述

我在 C# 中使用实体框架。我想在从数据库获取数据时排除一些列。例如,我的学生表有 10 列。并且表中有一些列,如 CreatedDate、CreatedBy、CreateRole、UpdatedDate、Updatedby、UpdatedRole。我想要在从数据库中获取列表时排除此列的通用解决方案,如下所示。

我正在寻找如下

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

请不要在以下解决方案中提供建议,因为这不是我想要的。

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

标签: c#entity-frameworklinq

解决方案


正如我的评论中所述,我将为仅偶尔需要的属性创建一个模型:

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
}

然后将此模型用作我的主要模型中的属性:

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

然后当您从实体框架中选择项目时,您可以使用

.Include(s => s.CreateAndUpdateProperties)

如果你想包含 create 和 update 属性。没有这个包括,它只是空的。


推荐阅读