1

我有以下更新方法:

        public Folder UpdateFolder(Folder folder)
        {
            _db.Folders.Attach(folder); // error happens here
            var entry = _db.Entry(folder);
            entry.Property(e => e.Title).IsModified = true;
            SaveChanges();
            return entry.Entity;
        }

当我尝试附加时,我得到“具有相同密钥的对象已经存在”。如果我删除该行,我会得到“此上下文中不存在类型为“文件夹”的实体”。

然后我尝试以下操作:

    public Folder UpdateFolder(Folder folder)
    {


        var entry = _db.Entry(folder);
        entry.State= EntityState.Detached;
        _db.Folders.Attach(folder);

        entry.Property(e => e.Title).IsModified = true;

当我调用 Attach 时,我得到了同样的错误。

这是我从(测试方法)调用它的地方:

        // Update Folder, Check Folder
        homeFolder.Title = "Updated";
        _dtoServices.UpdateFolder(homeFolder); // HERE
        Assert.AreEqual(_dtoServices.GetFolder(homeFolder.FolderId).Details, "Updated");

在我的 DtoServices 中:

        public FolderDto UpdateFolder(FolderDto folderDto)
        {     
            var test = _repository.UpdateFolder(folderDto.ToEntity());
            return null;
        }

在我的 FolderDto 中:

public class FolderDto
{
    public FolderDto()
    {
    }

    public FolderDto(Folder folder)
    {
        FolderId = folder.FolderId;
        Title = folder.Title;          
    }

    [Key]
    public int FolderId { get; set; }

    [Required]
    public string Title { get; set; }

    public Folder ToEntity()

     {
        var folder = new Folder
        {
            FolderId = FolderId,
            Title = Title,
        };
        return folder;
    }
 }

知道为什么会这样吗?如何为我的更新方法构建更强大的检查?我四处搜寻,但找不到任何结论性的东西。

4

1 回答 1

0

您必须确保该实体尚未附加。我做这样的事情(TEntity:类):

...
//See if entity is attached already and return if so.    
TEntity attached = GetAttached(entityToUpdate);

if(attached == null)
{
  //Entity is not attached, attach it.
}      
...

//Generic helper to check for attached entity
private TEntity GetAttached(TEntity aEntity)
{
  var lObjectContext = ((IObjectContextAdapter)context).ObjectContext;
  EntityKey lKey = GetEntityKey(aEntity);

  ObjectStateEntry entry;
  if (!lObjectContext.ObjectStateManager.TryGetObjectStateEntry(lKey, out entry)) return null;

  if (entry.State == EntityState.Detached) return null;

  return (TEntity)entry.Entity;
}
于 2013-03-12T04:34:32.730 回答