2016-04-27 7 views
1

は、ここで私はLINQ&Entity Frameworkどのようにオブジェクト全体を選択し、パラメータとして渡すか? <code>Product</code>と<code>ProductType</code>:

エンティティ7にするのは、私は2つのテーブルがあるとしましょう達成しようとしているものです。製品は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クラスから1つのプロパティが必要です。いくつかのラッパークラスを使用してトラフィックを最小限にしようとしていますが、そのために必要なコードを最小限に抑えようとしています。

しかし、私はまだこのアプローチがうまくいかない理由を知りたいと思います。 ありがとうございました!

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:.INCLUDE文を削除し、コメントでEVKのおかげで、作業のすべてを作りました。 それでも理由を知ることは興味深いでしょう。

+0

ProductとProductTypeのモデルを投稿できますか? –

+0

投稿をモデルで更新しました。ありがとう! – rook

+1

含める必要はありません(t => t.FK_ProductType)。あなたのコードでは何も役に立ちませんので、それを削除することができます(そして、これはあなたの質問に記載された問題を解決するかもしれません)。 – Evk

答えて

1

EF7バグかもしれませんか?この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(); 
+0

上記のEvkのコメントが問題を解決してから試したことはありませんでしたが、あなたの貢献に感謝します! – rook

関連する問題