Я пытаюсь сопоставить свойство Address модели представления со свойством address класса таблицы базы данных, используя .ProjectTo<POHeader, POHeaderViewModel()
, но получаю ошибку:
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
))