请考虑以下内容。
域实体
public class OwningType
{
public Guid Id { get; private set; }
public OwnedType Owned { get; private set; }
public OwningType()
{
Id = Guid.NewGuid();
}
public void SetOwned(string name)
{
if(Owned != null) throw new Exception("Already owned!");
Owned = new Owned(name);
}
}
public class OwnedType
{
public string Name { get; private set; }
public OwnedType(string name)
{
Name = name;
}
}
映射配置:
public override void Configure(EntityTypeBuilder<OwningType> builder)
{
base.Configure(builder);
builder.OwnsOne(x => x.OwnedType).WithOwner();
}
应用逻辑:
OwningType
实例并将其保存在数据库中。public void CreateNew()
{
var owning = new OwningType();
dbSession.Add(owning);
dbSession.SaveChanges();
}
OwningType
的位置发生了变化,我们需要添加Owned
实例。public void AddOwned(Guid owningId, string name)
{
var owning = dbSession.Get<OwningType>(owningId);
owning.SetOwned(name);
dbSession.SaveChanges();
}
导致以下异常:
System.InvalidOperationException:类型为'OwnedType'的实体与表类型为'OwningType'的实体共享表'OwningType',但是没有具有相同键值且已被标记为'Added'的该类型的实体。 考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看键值。
由于EF Core 3.0所有类型都可以为空。我想利用此功能在对象生命的后期实例化拥有的类型。在EF Core 3.0之前,必须实例化一个OwnedType
如何在不遇到changetracker问题的情况下更新Owned
的{{1}}属性?