![](/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.