【问题标题】:DbContext Set with where query using database first approach EFDbContext Set with where 查询使用数据库优先方法 EF
【发布时间】:2017-03-07 15:03:11
【问题描述】:

我有一个使用 ADO.NET 实体数据模型生成的类的数据库第一个项目。我所有的课程都有相同的布尔和日期时间字段,确定和日期。我想创建用于从 DbContext 检索 T 类的通用方法,但我不确定如何在该查询中使用 where,因为我无法访问 Ok 和 Date 字段。

注意:我无法更改生成的类,并且我想避免使用 Linq.Dynamic

ADO.Net 生成

public partial class First
{
    public int Id { get; set; }
    public string NameFirst { get; set; }
    public DateTime Date { get; set; }
    public bool Ok { get; set; }
}

public partial class Second
{
    public int Id { get; set; }
    public string NameSecond { get; set; }
    public DateTime Date { get; set; }
    public bool Ok { get; set; }
}

检索数据

public List<SomeModel> LoadFromDatabase<T>(bool ok, DateTime date)
{
    var dbData = DbContext.Set(typeof(T)).AsNoTracking().Where(x => x.Ok ??? );

    //remap to some model and return it
    ...

    return someModel;
}

编辑 1:

public List<SomeModel> LoadFromDatabase<T>(bool ok, DateTime date) where T : IDateOk 
{
    var dbData = DbContext.Set(typeof(T)).AsNoTracking().Where(x => x.Ok &&);

    //remap to some model and return it
    ...

    return someModel;
}

public interface IDateOk {
    DateTime Date { get; set; }
    bool Ok { get; set; }
}

编辑 2: 我在方法中缺少类,所以应该是这样的

public List<SomeModel> LoadFromDatabase<T>(bool ok, DateTime date) where T : class IDateOk 

【问题讨论】:

    标签: c# entity-framework dbcontext ef-database-first


    【解决方案1】:

    为通用属性定义一个接口:

    public interface IDateOk {
        DateTime Date { get; set; }
        bool Ok { get; set; }
    }
    

    这是一个如何将接口添加到生成的类的教程: Getting the Entity Framework to Generate an Interface for Mocking

    约束你的方法需要这个接口:

    public List<SomeModel> LoadFromDatabase<T>(bool ok, DateTime date) where T: IDateOk 
    

    现在您应该能够在实现中访问 OK 和 Date。

    【讨论】:

    • 我做了更改,您建议您可以在编辑 1 中看到它们,不幸的是,我在 dbData 查询中得到“无法解析符号确定”。你知道为什么吗?
    • 嗯,也许我没有想到这一点,EF 无法将查询转换为 SQL。要测试这个假设,请尝试通过首先枚举在内存中运行查询:var dbData = DbContext.Set(typeof(T)).AsNoTracking().ToList().Where(x =&gt; x.Ok);
    • 感谢您的帮助,让我找到了最终解决方案
    猜你喜欢
    • 1970-01-01
    • 2012-03-04
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多