我知道這個問題已經被問了很多次,但我認爲我指定修改字段的事實使它變得更難一些我解決。這是我的更新方法(在庫):ObjectStateManager中已存在具有相同鍵的對象(具有指定的字段)
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;
}
我得到「具有相同鍵的對象已存在」當我嘗試連接。如果我刪除該行,則會得到「此文本中不存在」文件夾類型的實體「。
這裏就是我從(測試方法)調用它:
homeFolder = _dtoServices.AddFolder(new FolderDto
{
Title = "Home Folder"
});
Assert.AreEqual(_dtoServices.GetHomeData().TotalFolders, 1);
// Check Folder
Assert.AreEqual(_dtoServices.GetFolder(homeFolder.FolderId).Details, "Home Folder");
// 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;
}
}
知道爲什麼這發生了什麼?