![](/img/trans.png)
[英]C# AutoMapper with Entity Framework - Works with List but not single nullable instance
[英]C# Automapper 6.1.1 - Collection/List destination properties loses values Entity Framework 6
使用Automapper 6映射集合時遇到問題,我找不到解決方案。 在下面的updatedArticle
對象中,由於視圖模型中不存在舊的“ Created
和“ Updated
值,因此映射后還保留了這些值。 但是,“描述”中“ Created
和“ Updated
的值將丟失。 通過視圖模型輸入的值均已正確更新。 我究竟做錯了什么? Automapper還丟失了Article的Entity Framework 6映射,因為這些值也丟失了。
控制器方式:
public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
return Ok();
}
制圖:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ArticleViewModel, Article>()
.ForMember(x => x.Created, opt => opt.Ignore())
.ForMember(x => x.Updated, opt => opt.Ignore());
cfg.CreateMap<DescriptionViewModel, Description>()
.ForMember(x => x.Created, opt => opt.Ignore())
.ForMember(x => x.Updated, opt => opt.Ignore())
.ForMember(x => x.ArticleId, opt => opt.Ignore())
.ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();
的ViewModels:
public class ArticleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<DescriptionViewModel> Descriptions { get; set; }
}
public class DescriptionViewModel
{
public int Id { get; set; }
public string Heading { get; set; }
}
楷模:
public class Article : IEntity<int>
{
public Article()
{
Descriptions = new List<Description>();
}
[Key]
public int Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
[MaxLength(256)]
public string Name { get; set; }
public virtual ICollection<Description> Descriptions { get; set; }
}
public class Description: IEntity<int>
{
[Key]
public int Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
[MaxLength(256)]
public string Heading { get; set; }
public int ArticleId { get; set; }
public virtual Article Article { get; set; }
}
您是否嘗試過不延遲加載? 我自己在EF Lazy Loading和AutoMapper方面遇到了一些問題。 首先,它效率很低。
參見相關的答案 。
經過兩天的挫折終於解決了。 從https://github.com/AutoMapper/AutoMapper.Collection安裝了AutoMapper.Collection
PM> Install-Package AutoMapper.Collection
PM> Install-Package AutoMapper.Collection.EntityFramework
我只需要更改cfg.AddCollectionMappers();
和EqualityComparison
。 例:
Mapper.Initialize(cfg =>
{
cfg.AddCollectionMappers();
cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();
cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
.EqualityComparison((src, dst) => src.Id == dst.Id);
cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
.EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.