我首先使用代码启动了一个示例项目,并从具有外键约束的实体获取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();
}
答案 0 :(得分:2)
变化:
public virtual IEnumerable<OrderItem> Order { get; set; }
要:
public virtual ICollection<OrderItem> Order { get; set; }
由于IEnumerable<>
公开了只读方法,Entity Framework
基本上忽略了它。该属性必须是可写的集合类型才能将其映射到数据库。
通常情况下,公开IEnumerable
属性并让getter
返回真正为backing-field
的{{1}}非常常见。
答案 1 :(得分:0)
您应该更改以下内容:
public IEnumerable<CustomerItem> GetOrdersFromCustomerItem(int id)
{
// You must select CustomerItem not a customer in the previous linq query.
return (from c in this.dax.Customer
where c.Id.CompareTo(id) == 0
select new CustomerItem{
}).AsEnumerable().ToList();
}