![](/img/trans.png)
[英]EF 6 Core prefix based on property of the entity in many-to-one relationship
[英]Configuring Many-to-One relationship correctly ef core
我在我的项目中使用 CQRS 模式。 我希望我的客户实体有可能拥有一组地址,因此我配置了一对多的 EF 关系。 但是,当我创建一个新客户然后检索它时,地址字段只是一个空数组:
{
"id": 1,
"firstName": "string",
"lastName": "string",
"phone": "string",
"email": "string",
"primaryContact": "string",
"secondaryContact": "string",
"addresses": [],
"orders": []
}
我对使用 AutoMapper 很陌生,所以我想知道我是否没有正确配置关系
客户实体:
public class Customer : AuditableEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string PrimaryContact { get; set; }
public string SecondaryContact { get; set; }
#region Navigation Properties
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Order> Orders { get; set; }
#endregion
}
地址实体:
public class Address : AuditableEntity
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
AddressDTO 只是地址实体中设置的属性,没有导航属性。
public class AddressCreateDto
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
GetCustomerByIdResponse
public class GetCustomerByIdResponse
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string PrimaryContact { get; set; }
public string SecondaryContact { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
我的自动映射器配置文件:
public AddressProfile()
{
CreateMap<AddressCreateDto, Address>().ReverseMap();
CreateMap<CreateCustomerCommand, Address>().ReverseMap();
}
public CustomerProfile()
{
CreateMap<CreateCustomerCommand, Customer>().ReverseMap();
CreateMap<GetCustomerByIdResponse, Customer>()
.ForMember(dst => dst.Orders, opt => opt.MapFrom(src =>
src.Orders))
.ReverseMap();
}
像您一样从预先编辑的帖子中修复关系后,我会检查并确保在使用 EF 检索Customer
实体时,您正在使用
Include(x => x.Addresses)
所以看起来有点像这样(简化版)
var customers = Customers
.Include(x => x.Addresses)
.Include(x => x.Orders)
.ToList();
否则 EF 核心不会从 db 中获取它们。 Orders
也是如此,它们需要单独的Include
声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.