Entityモデルに複合キーを設定する
Entityモデルに複合キー設定
MyViewModel.cs
public class MyViewModel { [Key] public string Clm1 { get; set; } [Key] public string Clm2 { get; set; } public string Clm3 { get; set; } }
実行してみると、取得時に以下のエラーになる。
型 'System.InvalidOperationException' の例外が EntityFramework.dll で発生しましたが、ユーザー コード内ではハンドルされませんでした 追加情報:Unable to determine composite primary key ordering for type 'myWeb.Models.MyViewModel'. Use the ColumnAttribute (see http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an order for composite primary keys.
原因は複合キーの順番が決まってないため
MyViewModel.csを以下の様に修正
public class MyViewModel { [Key] [Column(Order =0)] public string Clm1 { get; set; } [Key] [Column(Order =1)] public string Clm2 { get; set; } public string Clm3 { get; set; } }
ColumnAttributeで順番を設定することで解決出来る
検索時も以下の様に使用可能になる。
context.MyViewModels.Find("first","second")