【发布时间】:2021-10-07 08:47:48
【问题描述】:
下面的示例显示了客户和发票之间的简单一对多关系。 LINQ 查询检索所有发票和相关客户。我只是想对查询的效率有一个意见,因为就像一个发票有一个客户的递归,客户有很多发票,每个发票都有一个客户,等等。 另外,在只读场景中我可以使用 AsNoTracking() 吗?
public class Customer
{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
[ForeignKey("CustomerID")]
[NotMapped]
public virtual IList<Invoice> Invoices { get; set; }
}
public class Invoice
{
public int InvoiceID { get; set; }
public int CustomerID { get; set; }
[ForeignKey("CustomerID")]
public Customer Customer { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//........
builder.Entity<Invoice>().ToTable("Invoices")
.HasOne(s => s.Customer).WithMany(c => c.Invoices)
.OnDelete(DeleteBehavior.Restrict);
}
public class SomeClass
{
//....
List<Invoice> invList = await context.Invoices.Include(x => x.Customer).toListAsync();
}
【问题讨论】:
-
如果代码足够快,则无需尝试替代方案。所以你需要测量。尽可能首先编写代码以确保清晰和易于维护。
-
是的,用于只读方案
AsNoTracking可以使用,因为您不希望 EF 跟踪它。
标签: c# .net linq query-optimization