0

我首先使用代码启动了一个示例项目,并从具有外键约束的实体中获取 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();
}
4

2 回答 2

2

改变:

public virtual IEnumerable<OrderItem> Order { get; set; }

至:

public virtual ICollection<OrderItem> Order { get; set; }

由于IEnumerable<>暴露了只读方法,Entity Framework基本上是忽略它。该属性必须是可写集合类型才能将其映射到数据库。

但是,公开一个IEnumerable属性并让它getter返回一个backing-field实际上是一个IList/ICollection.

于 2013-05-19T13:15:12.050 回答
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();
}
于 2013-05-18T23:52:07.883 回答