我正在使用Visual Studio 2017和Entity Framework开发ASP.Net核心Web API。
我有以下InitialDeviceLocation
实体:
public class InitialDeviceLocation
{
[Required]
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("CampaignId")]
public Campaign Campaign { get; set; }
public Guid CampaignId { get; set; }
[Required]
public int DeviceId { get; set; }
[Required]
public int LocationId { get; set; }
}
我希望Automapper能够查找DeviceName
和LocationName
,因为它会将实体映射到我的DTO,但无法确定映射。
我无法将DeviceId
和LocationId
设置为外键,因为这会创建循环关系。我假设Automapper可以简单地查找这些字段,以便我可以为客户端提供这些字段。
我尝试使用.ForMember
,但由于我的实体定义中没有Device
个对象或Location
个对象,我无法看到如何执行此操作
以下是我的Device
实体定义,Locations
非常相似:
public class Device
{
[Required]
[Key]
public int Id { get; set; }
[ForeignKey("DeviceTypeId")]
public DeviceType DeviceType { get; set; }
public int DeviceTypeId { get; set; }
public string Ident { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
public int DefaultLocationId { get; set; }
}
任何建议都非常欢迎。感谢。
答案 0 :(得分:3)
首先,在Device
中添加Location
和InitialDeviceLocation
个实体。
public class InitialDeviceLocation
{
// Other properties
public virtual Device Device { get; set; }
public virtual Location Location { get; set; }
}
然后,在您的DTO中,您可以添加名为DeviceName
和LocationName
的属性。 AutoMapper将自动识别[ClassName][PropertyName]
的约定并为您执行映射。
public class InitialDeviceLocationDTO
{
// Other properties
public string DeviceName { get; set; }
public string LocationName { get; set; }
}