c# linq填充不映射属性

本文关键字:映射 属性 填充 linq | 更新日期: 2023-09-27 18:15:03

我首先使用实体框架代码,我有两个实体:

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
   };

c# linq填充不映射属性

您的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; }  }
}