在使用基于约定的导航时,我们可能会遇到一些问题。例如,在使用单向导航时,你不能访问导航到的实体的导航属性,因为它们未加载。同样,在使用双向导航时,你需要添加额外的逻辑来确保双向导航正确。
下面是一些示例代码,展示如何解决这些问题:
使用单向导航
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
}
// To access the Customer's orders, you need to explicitly include them
var customer = context.Customers
.Include(c => c.Orders)
.FirstOrDefault(c => c.CustomerId == 1);
// Alternatively, you can fetch the orders directly and then get the customer
var order = context.Orders
.Include(o => o.Customer)
.FirstOrDefault(o => o.OrderId == 1);
var customer = order.Customer;
使用双向导航
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public ICollection Orders { get; set; }
}
// Adding an order to a customer's orders should automatically set the customer
var customer = context.Customers.Find(1);
var newOrder = new Order { Customer = customer };
customer.Orders.Add(newOrder);
// Removing an order from a customer's orders should also update the order's customer reference
customer.Orders.Remove(order);
// To avoid null reference exceptions, we need to manually ensure both sides of the relationship are set
var customer = context.Customers.Include(c => c.Orders).FirstOrDefault(c => c.CustomerId == 1);
var newOrder = new Order();
customer.Orders.Add(newOrder);
newOrder.Customer = customer;
// Alternatively, you can use the DbSet.Local property to get all the tracked entities in memory
var orders = context.Orders.Local;
var customers = context.Customers.Local;