我有以下更新方法:
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;
}
}
知道为什么会这样吗?如何为我的更新方法构建更强大的检查?我四处搜寻,但找不到任何结论性的东西。