【发布时间】:2019-03-20 00:08:37
【问题描述】:
也许标题被误解了,但我会在这里尝试解释我的情况。
因此,考虑到我的实体 Person 具有虚拟属性 Country,如下所示:
public class Person {
public long Id { get; set;}
public short IdCountry { get; set;}
public virtual Country Country { get; set; }
...
}
映射如下:
...
builder.HasOne(c => c.Country)
.WithMany()
.HasForeignKey(c => c.IdCountry);
我的存储库是通用的。
这里发生的情况是,当我尝试在 Person 中保存一些更改时,Country 实体状态以 Added 的形式出现在我面前,这没有任何意义。
我在这里展示了一个类似的例子,说明发生在我身上的事情。实际上,我的班级中有五个其他虚拟属性Person,其中一些处于这种状态(Added)。
以前有人处理过吗? 提前致谢。
编辑:Ansewing @alans 回复:我正在做类似如下的事情:
foreach (var entrie in entry.Context.ChangeTracker.Entries())
{
try
{
key = entrie.Entity.GetType().GetProperty("Id").GetValue(entrie.Entity, null);
}
catch (Exception ex)
{
key = null;
}
if (key != null && entrie.State == EntityState.Added)
{
entrie.State = EntityState.Unchanged;
}
else if (Convert.ChangeType(key, typeof(long)) as long? == 0)
{
entrie.State = EntityState.Added;
}
}
_dbContext.SaveChanges();
@TanvirArjel 上面的这个方法是状态的来源Added
【问题讨论】:
-
您是否在更新时运行 TrackGraph?
-
@thatsallfolks 添加国家实体状态的代码在哪里?请将这些代码添加到问题中。
标签: c# entity-framework-core ef-core-2.1 change-tracking