获取本地实体或附加一个新实体

我的实体看起来像这样:


public class User

{

    public int Id {get; set;}

}

我不想在每次获得特定用户时查询数据库,其中我知道此 ID 存在用户。似乎 Attach 适用于这种情况,但是如果 DbContext 已经在本地存储了此特定用户的实体,它将引发异常。


例如我想做的事情:


var user1 = ctx.GetLocalOrAttach(new User{Id = 1});

var user2 = ctx.GetLocalOrAttach(new User{Id = 2});

AddUserRelation(user1, user2);

有什么解决办法吗?如果不是,检查本地是否存在实体的理想方法是什么。


SMILET
浏览 177回答 2
2回答

翻过高山走不出你

您可以搜索该DbSet<T>.Local属性,但这将是低效的。IMO 的更好方法是使用FindTracked我的回答中的自定义扩展方法,以在 EntityFrameworkCore 中按 ID 删除加载和卸载的对象using Microsoft.EntityFrameworkCore.Internal;namespace Microsoft.EntityFrameworkCore{&nbsp; &nbsp; public static partial class CustomExtensions&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public static TEntity FindTracked<TEntity>(this DbContext context, params object[] keyValues)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where TEntity : class&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var entityType = context.Model.FindEntityType(typeof(TEntity));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var key = entityType.FindPrimaryKey();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var stateManager = context.GetDependencies().StateManager;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var entry = stateManager.TryGetEntry(key, keyValues);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return entry?.Entity as TEntity;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这类似于 EF CoreFind方法,但如果实体在本地不存在,则不会从数据库加载实体。您的案例的用法如下:var user1 = ctx.FindTracked(1) ?? ctx.Attach(new User { Id = 1 }).Entity;var user2 = ctx.FindTracked(2) ?? ctx.Attach(new User { Id = 2 }).Entity;AddUserRelation(user1, user2);

DIEA

我多年来一直在使用 EF,但我从未使用过附加机制,它通常只会让您陷入困境。如果我查看代码,我猜您想在 2 个用户记录之间创建关系,但您想通过不查询两个用户记录来优化性能。(就我个人而言,我不会关心 20 毫秒的开销,它会花费我获取用户对象,但我想这可能很重要)。EF 允许您使用外键创建记录,而无需加载外部实体。因此,您可以从以下代码更改以下代码:var user1 = context.Users.Find(1);var user2 = context.Users.Find(2);var userRelation = new UserRelation();userRelation.FromUser = user1;userRelation.ToUser = user2;context.UserRelations.Add(userRelation);到 :var userRelation = new UserRelation();userRelation.FromUserId = 1;userRelation.ToUserId = 2;context.UserRelations.Add(userRelation);请注意,在我的上一个代码示例中,我没有查询两个用户对象,但 EF 将创建带有 2 个有效外键的 UserRelation 记录。
打开App,查看更多内容
随时随地看视频慕课网APP