【发布时间】:2019-06-23 10:01:19
【问题描述】:
我正在尝试使用 AutoMapper 将 EF 实体映射到我的服务模型,但在映射发生时出现错误。
例如:
服务模型类:
public class User
{
public Guid UserId {get; set;}
public string Name {get; set;}
public Company Company {get; set;}
}
public class Company
{
public Guid CompanyId {get; set;}
public string Name {get; set;}
public ICollection<User> Users {get; set;}
}
实体模型类:
public class UserData
{
public Guid Id {get;set;}
public string Name {get; set;}
public Guid CompanyId CompanyId {get; set;}
public virtual Company Company {get; set;}
}
public class CompanyData
{
public Guid Id {get; set;}
public string Name {get; set;}
public virtual ICollection<UserData> Users {get; set;}
}
AutoMapper 配置文件
用户映射
this.CreateMap<Data.Entities.UserData, Services.Models.User>()
.ForMember(u=>u.UserId, opt=>opt.MapFrom(u=>u.Id))
.ForMember(u=>u.Company, opt=>opt.MapFrom(u=>u.Company));
公司制图
this.CreateMap<Data.Entities.CompanyData, Services.Models.Company>()
.ForMember(o => o.CompanyId, opt => opt.MapFrom(o => o.Id))
.ForMember(o => o.Users, opt => opt.MapFrom(o => o.Users));
我收到以下错误:
AutoMapper.AutoMapperMappingException: 'Error mapping types.'
TypeLoadException: Method 'Add' in type
'Proxy_System.Collections.Generic.ICollection`1
[[MyCompany.Services.Models.User, MyCompany.Services, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null]]_19426640_' from assembly
'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral,
PublicKeyToken=be96cd2c38ef1005' does not have an implementation.
如果我从服务模型中删除 Users 属性,因此在我尝试映射公司时它不会尝试映射用户,它工作正常。当我映射用户并返回公司详细信息时,这也可以正常工作。
它显然与 Users 属性有关,但我不确定是什么。
谁能告诉我我做错了什么?
谢谢。
【问题讨论】:
-
复制会有所帮助。创建一个gist,我们可以执行并看到失败。
-
我猜自动映射器不像实体框架那样理解
System.Collections.Generic.ICollection<T>。尝试在Services.Models.Company中使用像System.Collections.Generic.HashSet<T>这样的具体类型。 -
您的对象映射中有一个无限循环。当您映射用户时,您映射用户的公司,然后在公司中映射所有用户,然后映射每个用户及其用户公司,依此类推......
-
@YairI 发现得很好。我刚刚完成了更改行为以删除这个无限循环:)
标签: c# entity-framework automapper