首页 > 解决方案 > EF Core 中的条件导航属性

问题描述

我有一个 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");

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

当然有一些方法可以做到这一点?

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

解决方案


我猜您要查找的内容(其中Include()使用Where()了子句),现在已添加到.net 5. 看看这个答案。


推荐阅读