这不是操作方法问题,而是操作原因和工作方式。就是这样,当一个人在他的assembly
中有两个namespaces
和两个contexts
实现了TPT
树的不同部分但共享了基表时,调用在抛出SaveChanges()
的上下文中使用UpdateException: Error retrieving values from ObjectStateEntry. See inner exception for details.
。内部异常指出
(41,10):错误3032:映射从行开始的片段时出现问题 41、47:EntityTypes app.a.ChildB, app.a.ChildA被映射到相同的 表xBase中的行。映射条件可用于 区分这些类型映射到的行。
第一个问题是这些行号是什么,它们指的是什么?
现在,给出代码:
namespace app
{
public abstract class xBase
{
//...
}
}
namespace app.a
{
public class ChildA : xBase
{
//...
}
public class AContext : DbContext
{
public DbSet<xBase> Base { get; set; }
public DbSet<ChildA> Children { get; set; }
public AContext()
: base("name=AppAContext")
{
this.Configuration.LazyLoadingEnabled = false;
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("PlayGround");
modelBuilder.Configurations.Add(new xBaseConfiguration());
modelBuilder.Configurations.Add(new ChildAConfiguration());
}
public class xBaseConfiguration: EntityTypeConfiguration<xBase>
{
public xBaseConfiguration()
{
//...
this.Map(m => {
m.ToTable("xBase");
});
}
}
public class ChildAConfiguration : EntityTypeConfiguration<ChildA>
{
public ChildAConfiguration ()
{
//...
this.Map(m => {
m.ToTable("AChildren");
});
}
}
}
}
namespace app.b
{
public class ChildB : xBase
{
//...
}
public class BContext : DbContext
{
public DbSet<xBase> Base { get; set; }
public DbSet<ChildB> Children { get; set; }
public BContext()
: base("name=AppBContext")
{
this.Configuration.LazyLoadingEnabled = false;
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("PlayGround");
modelBuilder.Configurations.Add(new xBaseConfiguration());
modelBuilder.Configurations.Add(new ChildBConfiguration());
}
public class xBaseConfiguration: EntityTypeConfiguration<xBase>
{
public xBaseConfiguration()
{
//...
this.Map(m => {
m.ToTable("xBase");
});
}
}
public class ChildBConfiguration : EntityTypeConfiguration<ChildB>
{
public ChildBConfiguration()
{
//...
this.Map(m => {
m.ToTable("BChildren");
});
}
}
}
}
N.B .:两个上下文使用不同的名称,但指向相同的数据库实例。
然后,当有人尝试添加时,f.e。新的ChildA
引发了上述异常,例如本例:
using (var db = new AContext())
{
var child = new AChild();
//...
db.Children.Add(child);
db.SaveChanges(); //<--At this point the exception is thrown
}
如果从组装中排除了树的任何一部分,则与第二部分一起运行的代码将按需工作。
现在,它可能与该行为相关,也可能与该行为无关,但是由于某种原因,正如我们在异常消息中所看到的那样,框架认为层次结构的两个部分都位于同一个命名空间中,事实并非如此,最初它们是,所以我从分离它们开始,但是什么都没有改变,然后分离了两个上下文使用的连接字符串,但仍然具有相同的行为。值得一提的是,即使仅实例化了一个上下文,并且在插入第一个孩子并调用SaveChanges()
时,也会引发异常。那么,一个上下文如何以及为什么知道另一个命名空间中存在其他实体?