我正在使用实体框架代码优先,我有两个实体:
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
};
但这没效果。
答案 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
};
但是,由于ProductStorage
和Product
共享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; } }
}