高效填充导航属性

问题描述 投票:0回答:1

我有一个复合模型,它从前端发布到我的 .NET core api。

目前我正在使用

DbSet<T>.Find(id)
方法分配给
Customer.City
属性。

是否有更有效的方法来从我的数据库中的关系数据填充导航属性,即城市。

D到

public class CustomerDto
{
    public int CustomerId { get; set; }
    public string Code { get; set; }
    public string DisplayName { get; set; }
    public int CityId { get; set; }
}

Dbcontext 中的实体

public class Customer : ISystemOperated, ICachable
{
    public int CustomerId { get; set; }
    public string? Code { get; set; }
    public string DisplayName { get; set; }
    public virtual City? City { get; set; }
}

自动映射器映射

CreateMap<CustomerDto, Customer>();
c# .net entity-framework-core core
1个回答
0
投票

在 EF Core 中,您无需手动执行此操作。您只需指定之间的关系 客户及城市:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .HasOne(c => c.City )
        .WithMany(ct => ct.Customer)
        .HasForeignKey(c => c.CityId);
}

此后,当您查询客户时,您只需包含城市:

public IEnumerable<Customer> GetCustomerAsync()
{
    return this.context.Customers
        .Include(x => x.City)                
        .ToListAsync();
}
© www.soinside.com 2019 - 2024. All rights reserved.