我是使用 Entity Framework 6 的新手,在尝试更新实体时遇到了困难。我正在使用 Code First 方法和我的模型,简化为有问题的类,如下所示:
public class Document
{
public long Key { get; set; }
public string Name { get; set; }
}
public class Batch
{
public long Key { get; set; }
public virtual List<Document> Documents { get; private set; }
public void Add(Document document)
{
Documents.Add(document);
}
public void Remove(Document document)
{
Documents.RemoveAt(Documents.FindIndex(d => d.Key == document.Key));
}
}
Batch 和 Document 之间存在一对多的关系,通过独立关联建模,因此没有显式 FK。 一个重要的特殊性是 Document 类不知道 Batch。这与 Stackoverflow 上的其他类似问题不同,例如 this one例如。 Entity Framework 在文档表中生成一个可为空的列 Batch_Key。
这是上下文类:
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Document>().HasKey(d => d.Key);
modelBuilder.Entity<Batch>().HasKey(b => b.Key);
modelBuilder.Entity<Batch>().HasMany(b => b.Documents).WithOptional().WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
}
我有一个带有 Update() 方法的 BatchRepository 类,该方法接收 Batch 参数并更新数据库中的批处理:
public class BatchRepository
{
public void Update(Batch item)
{
using (var dbCtx = new MyDbContext(DBContextName))
{
batchesContext.Batches.Attach(item);
batchesContext.Entry(item).State = EntityState.Modified;
batchesContext.SaveChanges();
}
}
}
这是一个使用 Update() 方法从批处理中删除文档的单元测试:
[TestMethod]
public void CheckRemoveDocument()
{
var batches = BatchRepository.FindAll().ToList();
var batch = batches[0];
var batchKey = batches[0].Key;
var doc = batch.Documents[0];
int batchNumberOfDocuments = batch.Documents.Count;
batch.Remove(doc);
BatchRepository.Update(batch);
batch = BatchRepository.FindBy(batchKey);
Assert.AreEqual(batchNumberOfDocuments - 1, batch.Documents.Count);
}
测试失败,batchNumberOfDocuments和之前一样。如果我实现一种方法来从一批中删除所有文档,如下所示:
public class BatchRepository
{
public void RemoveDocuments(Batch item)
{
using (var dbCtx = new MyDbContext(DBContextName))
{
var existingBatch = batchesContext.Batches.Find(item.Key);
batchesContext.Entry(existingBatch).Collection(b => b.Documents).Load();
existingBatch.Documents.RemoveAll(d => true);
batchesContext.SaveChanges();
}
}
}
以下测试成功:
[TestMethod]
public void CheckRemoveAllDocuments()
{
var batches = BatchRepository.FindAll().ToList();
var batch = batches[0];
var batchKey = batches[0].Key;
BatchRepository.RemoveDocuments(batch);
batch = BatchRepository.FindBy(batchKey);
Assert.AreEqual(0, batch.Documents.Count);
}
因此 EF 正确地跟踪批处理和文档之间的关系,将删除的文档的 Batch_Key 列设置为 NULL。为什么这在这种情况下有效,但在我正在更新的情况下却无效?我假设这是因为链接到批处理的文档实体没有附加到上下文。问题是我不知道来自 Update() 方法参数的批处理是否包含更多文档、更少文档或完全不同的文档列表(另外,可能是文档列表以外的其他内容)改变了)。
这样的实现:
public class BatchRepository
{
public void Update(Batch item)
{
using (var dbCtx = new MyDbContext(DBContextName))
{
var existingBatch = batchesContext.Batches.Find(item.Key);
batchesContext.Entry(existingBatch).Collection(b => b.Documents).Load();
foreach (var doc in item.Documents)
{
batchesContext.Documents.Attach(doc);
batchesContext.Entry(doc).State = EntityState.Modified;
}
batchesContext.SaveChanges();
}
}
}
抛出异常:
System.InvalidOperationException: Attaching an entity of type 'Document' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
应该如何实现 Update() 方法才能正确执行更新?
谢谢您,如果问题听起来令人困惑,我深表歉意,这都是因为我对 EF 的困惑。
请您参考如下方法:
很明显,当您从上下文中断开一个实体时,它的状态不会被跟踪。因此,正如您所做的那样,您需要将实体附加回上下文并设置正确的状态。
问题是,当断开连接的实体是断开连接的树的根时,您必须处理相关实体。有多种可能的方法:
- 使用
Attach():在这种情况下,您需要单独附加每个实体,并设置每个实体的状态。 - 使用
Add():在这种情况下,整个树立即被附加,并且所有实体都获得已添加状态。因此,您需要设置每个实体的状态,新实体除外(因为它们已经具有Added状态)。
请注意,此行为是可取的。例如,如果您有多对多关系,新的 child 可能是全新的(添加的)或预先存在的(未更改的)。或者,您可以拥有一个具有一对多关系的父实体,该实体与已移除的子实体(已删除)和新实体(已添加)。因此,您始终必须跟踪每个实体的一组状态。
