1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

EntityFrameworkでunion

Posted at

Union

class ItemA
{
    public long Id;
    public string Name;
    public int Category;
}

class ItemB
{
    public long Id;
    public int Type;
}

上記二つのテーブルをunionするパターン

まずunionの結果となるクラスを作成する必要があります

class UnionFormat
{
    public long ItemAId;
    public long ItemBId;
    public string Name;
    public int Category;
    public int Type;
}

実際にunionしますが、クエリが発行されるのはToListが実行されたタイミングです。

//ItemAのテーブル
 IQueryable<UnionFormat> ItemAQuery = db.ItemAs.Select(x =>
  new UnionFormat
  {
    ItemAId = x.Id,
    Name = x.Name,
    Category = x.Category,
    // unionするためになにか値を指定する必要がある 
    ItemBId = 0,
    Type = 0,
  });

//ItemBのテーブル
 IQueryable<UnionFormat> ItemBQuery = db.ItemBs.Select(x =>
  new UnionFormat
  {
    ItemAId = 0,
    Name = "",
    Category = 0, 
    ItemBId = x.Id,
    Type = x.Type,
  });

// クエリ発行、.Unionで何個でもテーブルを連結できます。
List<UnionFormat> unionResult = ItemAQuery.Union(ItemBQuery).ToList();
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?