c #linq填充不映射属性

时间:2013-05-24 07:39:36

标签: c# entity-framework linq-to-sql

我正在使用实体框架代码优先,我有两个实体:

public class Product 
{
    public int ProductID { get; set; }     
    public decimal Price { get; set; }
    public int ProductCategoryID { get; set; }
    public virtual ProductCategory ProductCategory { get; set; }

    [NotMapped]
    public int Quantity { get; set; }
} 

public class ProductStorage
{
  [Key]
  public int ProductId { get; set; }


  [ForeignKey("ProductId")]
  public virtual Product Product { get; set; }

  public int Quantity { get; set; }

}

我似乎无法将Product列表填入Quantity属性。

我试过

from pr in repository.Query<Product>()
   join st in repository.Query<ProductStorage>() on pr.ProductID equals st.Quantity
   select new Product()
   {
       ProductID = pr.ProductID,
        ....
       Quantity = st.Quantity

   };

但这没效果。

1 个答案:

答案 0 :(得分:2)

Join已完成On错误字段,请尝试以下操作:

from pr in repository.Query<Product>()
join st in repository.Query<ProductStorage>() on pr.ProductID equals st.ProductID 
select new Product()
   {
   ProductID = pr.ProductID,
        ....
   Quantity = st.Quantity
   };

但是,由于ProductStorageProduct共享ProductId字段,这意味着您可以将它们以一对一的关系关联,例如:

public class Product 
{
    public int ProductID { get; set; }     
    public decimal Price { get; set; }
    public int ProductCategoryID { get; set; }
    public virtual ProductCategory ProductCategory { get; set; }
    public virtual ProductStorage Storage { get; set; }

    [NotMapped]
    public int Quantity { get { return this.Storage.Quantity; }  }
}