okinawa

IT勉強メモ

テーブル結合とViewModel

・参考

複雑なクエリ演算子 - EF Core | Microsoft Docs

ViewModelの作成

ここで言うViewModelとはテーブル結合の結果表示用のモデルクラス。

public class Blog
{
public int BlogId { get; set; }
public string Url { 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; } //外部キー
}

上記のBlogテーブルとPostテーブルの結合結果表示用のViewModel↓

2つのモデルクラスをがっちゃんこするだけ。

public class BlogPostViewModel
{
public int BlogId { get; set; }
public string Url { get; set; }
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}

テーブル結合

var query = from blog in context.Set<Blog>()
            join post in context.Set<Post>()
                on blog.BlogId equals post.BlogId
            select new BlogPostViewModel{ BlogId = blog.BlogId, Url = blog.Url, PostId = post.PostId, Title = post.Title, Content = post.Content };