我知道这个问题已经被问过很多次了,但我认为我指定修改字段的事实让我更难解决。这是我的更新方法(在存储库中):
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;
}
}
知道为什么会这样吗?