排除使用Entity Framework获取数据的列 [英] Exclude columns getting data with Entity Framework

查看:166
本文介绍了排除使用Entity Framework获取数据的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我在找下面的东西

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

请不要在下面的解决方案中提出建议,因为这不是我想要的.

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

推荐答案

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

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

然后,当您从Entity Framework中选择项目时,可以使用

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.

这篇关于排除使用Entity Framework获取数据的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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