2

ASP.NET MVCコアプロジェクトの次のLINQクエリで、次のエラーが発生していますUnable to cast object of type 'System.Linq.Expressions.NewExpression' to type 'System.Linq.Expressions.MemberExpression'LINQクエリで "Include"メソッドを使用するとエラーが発生する

public async Task<IActionResult> Index() 
{ 
    var qry = from b in _context.Blogs 
       join p in _context.Posts on b.BlogId equals p.BlogId into bp 
       from c in bp.DefaultIfEmpty() 
       select new { b.BlogId, b.Url, c.Title, c.Content, c.Blog }; 
    var bloggingContext = qry.Include(p => p.Blog); 
    return View(await bloggingContext.ToListAsync()); 
} 

モデル:このofficial ASP.NET tutorialからのエラーは、以下のコードの最後の行で発生します。

namespace ASP_Core_Blogs.Models 
{ 
    public class BloggingContext : DbContext 
    { 
     public BloggingContext(DbContextOptions<BloggingContext> options) 
      : base(options) 
     { } 

     public DbSet<Blog> Blogs { get; set; } 
     public DbSet<Post> Posts { get; set; } 
    } 

    public class Blog 
    { 
     public int BlogId { get; set; } 
     public string Url { get; set; } 

     public List<Post> Posts { get; set; } 
    } 

    public class Post 
    { 
     public int PostId { get; set; } 
     public string Title { get; set; } 
     public string Content { get; set; } 

     public int BlogId { get; set; } 
     public Blog Blog { get; set; } 
    } 
} 
+6

なぜこれがうまくいくと思うのかよく分かりません。あなたは匿名型を推測していますが、エンティティを含めることを期待していますか?ナビゲーションプロパティはどこにありますか? –

+0

「ブログ」モデルのコードを入力できますか? – Sampath

+0

@Sampath確かに、この[公式ASP.NETチュートリアル](https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html#create-your-model)から。しかし、参考のために、私があなたの要望に応じて、私はそれを**モデル**セクションの私のポストに含めました。 – nam

答えて

1

匿名タイプのIQueryableには使用できません。インクルードはナビゲーションプロパティを熱心に読み込むためのメソッドです。ナビゲーションプロパティを持つEntityのIQueryableでのみ使用できます。 一般的な使用方法:

var qry = _context.Blogs.Include(p=>p.Posts).ToArray(); 

それは、各ポストにロードされたブログでポストの配列を返します。

+0

私は自分のミスを理解するのに役立ちましたので、あなたの解決策を簡単に説明しました。 – nam

関連する問題