我首先使用代码启动了一个示例项目,并从具有外键约束的实体中获取 NULL 值。
我的模型:
public class CustomerItem
{
[Key]
public int Id { get; set; }
public int Name{get;set;}
public virtual IEnumerable<OrderItem> Order { get; set; }
}
public class OrderItem
{
[Key]
public int Id { get; set; }
[ForeignKey("CustomerItem")]
public int CustomerId { get; set; }
public virtual CustomerItem CustomerItem { get; set; }
}
dataaccess linq 查询以获取值:
public IEnumerable<CustomerItem> GetOrdersFromCustomerItem(int id)
{
return (from c in this.dax.Customer
where c.Id.CompareTo(id) == 0
select c).AsEnumerable().ToList();
}
这个查询返回 NULL 订单,所以我认为这个查询有一些错误。我怎样才能用外键表连接这个实体?
谢谢
更新了我的查询以使所有客户(及其订单)都达到此目的:
public IEnumerable<CustomerItem> GetAllCustomers()
{
return (from c in this.dax.Customer
select new
{
//Properties
OrderItem = c.OrderItem
}).AsEnumerable.ToList().select(s => new CustomerItem
{
//Properties
OrderItem = s.OrderItem, //here I got the exception I wrote in comment
}).ToList();
}