我有以下代码:
using (var db = new SourceLogContext())
{
db.LogEntries.Attach(this);
db.Entry(this).Collection(c => c.ChangedFiles).Load();
}
我得到以下异常:
System.InvalidOperationException occurred
Message=Conflicting changes to the role 'LogEntry_LogSubscription_Target' of the relationship 'SourceLog.Model.LogEntry_LogSubscription' have been detected.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityCollection`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.WalkObjectGraphToIncludeAllRelatedEntities(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClass2.<Attach>b__1()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
at System.Data.Entity.DbSet`1.Attach(TEntity entity)
at SourceLog.Model.LogEntry.LoadChangedFiles() in C:\github.com\tomhunter-gh\SourceLog\SourceLog.Model\LogEntry.cs:line 62
InnerException: (empty)
LogEntry 在此处分配了 LogSubscription:https ://github.com/tomhunter-gh/SourceLog/blob/443fb74a37db89522f85b4dfc941c52922785e7a/SourceLog.Model/LogSubscription.cs#L88
看起来该分配创建了一个新的 LogSubscription 实例并对其进行分配,然后 Attach 引用了一个不同的实例(但具有相同的 Id)。为什么这会导致错误,我将如何避免它?
在 LogSubscription L88 中,我基本上是在尝试将 LogEntry 添加到 LogSubscription 的集合属性中,但没有加载整个 LogEntry 集合。这是正确的方法吗?