LoginSignup
3
2

More than 3 years have passed since last update.

Entity Framework Coreでクラスをメンバとして扱う方法

Last updated at Posted at 2020-01-23

はじめに

日頃からEF Coreを多用しているじゅううんです。

ちょっとハマったことがあったので備忘程度に書いておきます。

コードファーストのマイグレーションが通らない

以下のようなクラスでコードファーストマイグレーションを行おうとしました。

public class Person
{
  public int Id { get; set; }
  public GeoCoordinate Position { get; set; }
}

public class GeoCoordinate
{
  public double Latitude { get; set; }
  public double Longitude { get; set; }
}

理想としてはこういうテーブルができてほしい

カラム名
Id int
Position_Latitude double
Position_Longitude double

> Add-Migration init
The entity type 'GeoCoordinate' requires a primary key to be defined.

できない

なぜ

  1. EFがGeoCoordinateを外部キーとして認識
  2. テーブルを作ろうとする
  3. [Key]属性がないので主キーが見つからないとエラーが出る

解決策

public class GeoCoordinate
{
  public double Latitude { get; set; }
  public double Longitude { get; set; }
}

これを

[Owned]
public class GeoCoordinate
{
  public double Latitude { get; set; }
  public double Longitude { get; set; }
}

とするだけです。

image.png

できました。

おわり。

3
2
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
3
2