c# - 排除使用实体框架获取数据的列
问题描述
我在 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();
解决方案
正如我的评论中所述,我将为仅偶尔需要的属性创建一个模型:
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 属性。没有这个包括,它只是空的。
推荐阅读
- batch-file - 无法在批处理脚本中使用 nssm set 命令
- oracle - 避免为两个提供者 pl/sql 插入相同的帐号 (RIB)
- angular - 可展开/可折叠图标菜单
- entity-framework - Entity Framework 6 Weak Entity 映射期望在添加迁移时出现一个键
- css - 仅为外部组件启用滚动条
- javascript - Ext.tree.Panel 中的 Extjs fieldLabel
- airflow - DummyOperator 在 Airflow 中的用途是什么?
- javascript - 如何在 before 钩子中插入流星集合?
- node.js - Angular 8 localhost:4200 not found 并且“ng serve”不起作用
- javascript - reactjs中如何将props从父组件传递给子组件