我正在尝试使用.ProjectTo<POHeader, POHeaderViewModel()
从数据库表类的address属性映射视图模型的Address属性,但是出现错误:
The entity or complex type 'Address' cannot be constructed in a LINQ to Entities query.
我只是在语法上错误地执行了此操作,或者这是不可能的,我需要展平视图模型以包括每个地址字段,或者让它继承自Address
并显式映射这些字段?
数据库表:
public partial class POHeader
{
public int Id { get; set; }
public int FacilityId{ get; set; }
public int? ShipToAddressId { get; set; }
public virtual Facility Facility { get; set; }
public virtual Address ShipToAddress { get; set; }
}
查看模型
public class POHeaderViewModel
{
public int Id { get; set; }
public int? ShipToAddressId { get; set; }
public Address ShipToAddress { get; set; }
}
地图
CreateMap<POHeader, POHeaderViewModel>(MemberList.Destination)
.ForMember(dest => dest.ShipToAddress, opt => opt.MapFrom(source => source.Address != null
?
new Address()
{
CompanyName = source.Address.CompanyName,
Address1 = source.Address.Address1,
Address2 = source.Address.Address2,
City = source.Address.City,
StateOrRegionCode = source.Address.StateOrRegionCode,
PostalCode = source.Address.PostalCode,
CountryCode = source.Address.CountryCode,
PhoneNumber = source.Address.PhoneNumber,
}
: new Address() {
CompanyName = source.Facility.Company.CompanyName,
Address1 = source.Facility.Address1,
Address2 = source.Facility.Address2,
City = source.Facility.City,
StateOrRegionCode = source.Facility.State,
PostalCode = source.Facility.PostalCode,
CountryCode = "US",
PhoneNumber = source.Facility.PhoneNumber,
}))
更新1:
我尝试将Facility
添加到Address
地图:
CreateMap<Facility, Address>(MemberList.Destination)
.ForMember(dest => dest.CompanyName, option => option.MapFrom(entity =>
entity.Company != null
? entity.Company.CompanyName
: "")
)
.ForMember(dest => dest.FirstName, option =>option.Ignore())
.ForMember(dest => dest.LastName, option => option.Ignore())
.ForMember(dest => dest.Address3, option => option.Ignore())
.ForMember(dest => dest.StateOrRegionCode, option => option.MapFrom(entity => entity.State))
.ForMember(dest => dest.CountryCode, option => option.MapFrom(entity => entity.Country))
然后将POHeaderViewModel
映射更改为以下内容……但出现错误:Type of conditional expression cannot be determined because there is no implicit conversion between 'Address' and 'Facility'
CreateMap<POHeader, POHeaderViewModel>(MemberList.Destination)
.ForMember(dest => dest.ShipToAddress, c => c.MapFrom(m =>
m.Address != null
? m.Address
: m.Facility
))