以下是一个示例代码,演示如何使用导航属性来返回所有记录而不仅仅是添加的属性:
// 定义模型类
public class Order
{
public int OrderId { get; set; }
public string OrderNumber { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public List Orders { get; set; }
}
// 在数据库上下文类中配置模型类
public class ApplicationDbContext : DbContext
{
public DbSet Orders { get; set; }
public DbSet Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasOne(o => o.Customer)
.WithMany(c => c.Orders)
.HasForeignKey(o => o.CustomerId);
}
}
// 使用导航属性返回所有记录
using (var context = new ApplicationDbContext())
{
var orders = context.Orders.Include(o => o.Customer).ToList();
foreach (var order in orders)
{
Console.WriteLine($"Order Number: {order.OrderNumber}, Customer Name: {order.Customer.CustomerName}");
}
}
在上述代码中,我们首先定义了两个模型类Order和Customer,它们之间有一个一对多的关系。然后在数据库上下文类ApplicationDbContext中配置了模型类之间的关系。最后,在使用上下文查询订单数据时,使用Include方法来包括导航属性Customer,从而返回所有记录包括相关的Customer信息。