型號我有一個支架型號:映射DTO回用AutoMapper
public partial class Fixture
{
public int FixtureId { get; set; }
public string Season { get; set; }
public byte Week { get; set; }
//foreign key
public int AwayTeamId { get; set; }
//navigation properties
public virtual Team AwayTeam { get; set; }
//foreign key
public int HomeTeamId { get; set; }
//navigation properties
public virtual Team HomeTeam { get; set; }
public byte? AwayTeamScore { get; set; }
public byte? HomeTeamScore { get; set; }
}
以及器具DTO:
public class FixtureDTO
{
public int Id { get; set; }
public string Season { get; set; }
public byte Week { get; set; }
public string AwayTeamName { get; set; }
public string HomeTeamName { get; set; }
public byte? AwayTeamScore { get; set; }
public byte? HomeTeamScore { get; set; }
}
我使用AutoMapper的映射,這是使用它我第一次嘗試。這裏是我的映射:
CreateMap<Fixture, FixtureDTO>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.FixtureId))
.ForMember(dest => dest.AwayTeamName, opt => opt.MapFrom(src => src.AwayTeam.TeamName))
.ForMember(dest => dest.HomeTeamName, opt => opt.MapFrom(src => src.HomeTeam.TeamName));
CreateMap<FixtureDTO, Fixture>();
它可以在拍攝夾具並將其映射到FixtureDTO,我用它來顯示數據正常。但是,當我想更新數據並通過FixtureDTO回映射回夾具我得到一個錯誤。
public HttpResponseMessage PutFixture(int id, FixtureDTO fixture)
{
if (ModelState.IsValid && id == fixture.Id)
{
//do mapping manually here?
var updated = _repository.UpdateFixture(Mapper.Map<Fixture>(fixture));
return Request.CreateResponse(updated ? HttpStatusCode.OK : HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
這是錯誤我得到:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
任何人可以在這方面幫助?
編輯:當實體您嘗試這通常發生:反向映射:
CreateMap<Fixture, FixtureDTO>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.FixtureId))
.ForMember(dest => dest.AwayTeamName, opt => opt.MapFrom(src => src.AwayTeam.TeamName))
.ForMember(dest => dest.HomeTeamName, opt => opt.MapFrom(src => src.HomeTeam.TeamName));
CreateMap<FixtureDTO, Fixture>()
.ForMember(dest => dest.FixtureId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.AwayTeam.TeamName, opt => opt.MapFrom(src => src.AwayTeamName))
.ForMember(dest => dest.HomeTeam.TeamName, opt => opt.MapFrom(src => src.HomeTeamName));
我認爲這是正確的軌道,但我有一個事實,即我有超過1個團隊對象的問題,並且映射不會映射TeamId,所以我最終得到2個0的teamId,這導致此錯誤:'具有相同密鑰的對象已經存在於ObjectStateManager中。 ObjectStateManager不能使用同一個鍵'追蹤多個對象'。我是否需要進入數據庫並映射TeamIds? – user517406
問題中沒有足夠的信息來定義'Team'應該如何映射,所以我簡單地調整了你的映射。您有幾個選項,可以在原始請求中獲取'Team.ID',並通過視圖中的隱藏字段保存它,或者使用團隊名稱查詢數據庫以在回發期間再次檢索ID。 – Mightymuke