LINQ&实体框架。如何选择整个对象并作为参数传递?

时间:2016-04-27 00:27:23

标签: entity-framework linq entity-framework-core

这是我在实体7中想要实现的目标。

假设我有两个表:ProductProductType。产品有ProductTypeId - FK到ProductType。我需要从ProductType中选择整个产品对象和一个属性,并将它们组合在这个类中:

public class MyData
{
    public string StringProperty {get; set;}
    public Product ClassProperty {get; set;}
}

现在出现了疑问:

var productId = 1; //example

database.Products
    .Include( t => t.FK_ProductType)
    .Where(p => p.ProductId == productId)
    .Select(result =>
            new MyData
              {
                StringProperty = result.FK_ProductType.ProductTypeDescription, //this works
                ClassProperty = result //this doesn't
              }
           );

我得到的错误是:无法将“System.Linq.Expressions.FieldExpression”类型的对象强制转换为“System.Linq.Expressions.ParameterExpression”。

PS:在仔细观察之后,我认为首先走这条路可能不是一个好主意。即使它有效MyData.ClassProperty也会附加所有ProductType表,而这不是我需要的。我只需要Product类和ProductType类中的一个属性。尝试通过使用一些包装类来最小化流量,但也尝试最小化所需的代码。

但我仍然想知道为什么这种方法不起作用。 谢谢!

UPD :在评论中为每个请求添加实体模型模型。

public class Product
{
    public int ProductId {get; set;}
    public string ProductName {get; set;}
    public int FK_ProductTypeId {get; set;} //this is our link to ProductType

    public virtual ProductType FK_ProductType {get; set;} //joined ProductType
}

public class ProductType
{
    public int ProductTypeId {get; set;} //our FK
    public string ProductTypeDesr {get; set;}
    //And Entity creates this
    public virtual ICollection<Product> {get; set;} = new HashSet<Product>();
}

UPD2 :感谢评论中的Evk,删除.Include语句使一切正常。 知道原因仍然很有意思。

1 个答案:

答案 0 :(得分:1)

可能是EF7的bug?看看这个discussion 。您也可以尝试这个解决方案:

var query = (from product in database.Products
            where product.ProductId == productId
            join type in database.ProductTypes 
            on product.FK_ProductTypeId equals type.ProductTypeId
            select new {
               ClassProperty = product,
               StringProperty = type.ProductTypeDescription
            }).FirstOrDefault();
相关问题