[英]InvalidOperationException: The instance of entity cannot be tracked - EF Core
[英]EF Core Get tracked entity by clone
简单问题:如何使用克隆(相同的主键值)获取被跟踪的实体。 由于映射,我没有被跟踪的实体,而是它的一个克隆。 如果使用 IClonable 或像 Mapster 这样的映射(适应相同的类型,或者在我的例子中是基本类型),如何获得克隆并不重要。 我想避免在不必要时执行查询。
我尝试了什么:
dbContext.Entry(clone) // ---> Always detached even if a tracked entity exists
dbContext.Table.FindAsync(clone) // ---> Crashed because clone is no primary key value
因为我可以使用dbContext.Table.FindAsync([primary/composite key values])
。 但是,如果复合键在迁移中发生变化怎么办。 例如,当您从 MySQL 迁移到 Postgres 并且您存储例如 GPS 坐标时,不是在纬度/经度中而是在点 object 中。
解决方案:
public static class DbContextExtensions {
public static async Task<TEntity?> FindTrackedAsync<TEntity>(this DbContext context, TEntity entity) where TEntity : class {
var entityType = context.Model.FindRuntimeEntityType(typeof(TEntity));
var keyProperties = entityType?.FindPrimaryKey()?.Properties;
if (keyProperties is null)
return null;
var keyValues = keyProperties.Select(prop => prop.GetGetter().GetClrValue(entity)).ToArray();
return await context.FindAsync<TEntity>(keyValues);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.