は、ここで私は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のおかげで、作業のすべてを作りました。 それでも理由を知ることは興味深いでしょう。
ProductとProductTypeのモデルを投稿できますか? –
投稿をモデルで更新しました。ありがとう! – rook
含める必要はありません(t => t.FK_ProductType)。あなたのコードでは何も役に立ちませんので、それを削除することができます(そして、これはあなたの質問に記載された問題を解決するかもしれません)。 – Evk