【问题标题】:Conditional navigation properties in EF CoreEF Core 中的条件导航属性
【发布时间】:2020-02-23 06:18:43
【问题描述】:

我有一个 User 表,其中有一个对应的 UserAudits 表来跟踪更改。操作类型存储在审计表中(插入、更新、删除)。

我想在我的用户实体上创建一个导航属性,以便我可以从审计表中获取“插入”记录。这可能吗?通常在设置导航属性时,无法在连接上指定额外条件。

用户:

public class User
{
    public int Id {get; set;}
    public string Name {get;set;}
    public UserAudit InsertedAuditRecord {get; set;} // <-- How to configure this?
}

用户审核:

public class UserAudit
{
    public int AuditId {get; set;
    public int Id {get; set;}
    public string Name {get; set;}
    public string OperationType {get; set;}
}

我知道我可以在我的用户实体上创建一个一对多的导航属性,然后查询:

ICollection<UserAudit> UserAudits {get; set;}
UserAudit InsertedAuditRecord => UserAudits.First(ua => ua.OperationType = "insert");

但这需要将用户的整个审计表放入内存中才能找到一条记录。

肯定有办法做到这一点吗?

【问题讨论】:

  • 哪个 EF 核心版本?
  • @GertArnold 我目前使用的是 2.2.2,但如果有必要可以升级到 3,因为我的应用程序仍在开发中。

标签: c# sql-server .net-core entity-framework-core


【解决方案1】:

我猜你正在寻找什么(这是 Include() 在其中使用 Where() 子句),现在已添加到 .net 5。看看this的答案。

【讨论】:

    【解决方案2】:

    子记录上的Where (First) 不会带回整个子对象。

    【讨论】:

    • 请您详细说明一下?
    • 查询时你的sql是什么?
    • 如果我使用的是ICollection&lt;UserAudit&gt;,则它为空,除非我调用Include(u =&gt; u.UserAudits),这会带回所有记录。
    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 2018-10-10
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2022-01-04
    相关资源
    最近更新 更多