我有一個具有以下結構的實體框架POCO。使用Automapper將DTO映射到實體
public class Entity
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
我創建了一個數據傳輸對象,供我的視圖使用該實體。
public class EntityDto
{
public int Id { get; set; }
public string Name { get; set; }
}
現在,我的Global.asax文件中有以下映射代碼。
Mapper.CreateMap<Entity, EntityDto>();
Mapper.CreateMap<EntityDto, Entity>(); // not sure whether I need this as well?
一切工作正常,我通過DTO我的意見確定,我可以從我EntityDto
模型創建的Entity
一個新的實例。當我嘗試編輯我的Entity
時出現問題;我意識到這是AutoMapper失去EF創建的實體關鍵字來跟蹤對象的變化,但通過幾個來源閱讀,似乎並沒有一個明確的解決方案。這是我用來編輯我的實體的操作。
public ActionResult EditEntity(EntityDto model)
{
var entity = context.Entities.Single(e => e.Id == model.Id);
entity = Mapper.Map<EntityDto, Entity>(model); // this loses the Entity Key stuff
context.SaveChanges();
return View(model);
}
現在,我該怎麼做才能解決這個問題?我可以:
- 不知何故告知AutoMapper的
.Ignore()
實體密鑰屬性? - 獲取AutoMapper複製實體密鑰屬性?
.Attach()
我的地圖Entity
並設置狀態爲已修改?
任何幫助總是讚賞。
輝煌,這只是工作。給我一些時間來嘗試我的實際項目。 –
這正是我正在尋找的,再次感謝! –
很高興我可以alt選項卡和複製粘貼..我的意思是幫助你。 :) – Pluc