5

非常に単純に、私は[ForeignKey(..)]属性を代わりにmodelBuilderの流暢な呼び出しに置き換えたいと思います。明示的な外部キープロパティ(CreatedBySessionId)と関連付けられたナビゲーションプロパティ(CreatedBySession)を関連付けるWithRequired(..)およびHasForeignKey(..)と同様のもの。しかし、私は1対1の対話のためにこれを1対多の対話の代わりにしたいと考えています。EF 4.1コードファーストModelBuilder 1対1リレーションシップのHasForeignKey

modelBuilder.Entity<..>().HasMany(..).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId) 

より具体的な例を以下に示します。これは[ForeignKey(..)]属性でとてもうまく動作しますが、モデルビルダーで純粋にそれをやり直して設定したいと思います。ここで

public class VendorApplication 
{ 
    public int VendorApplicationId { get; set; } 

    public int CreatedBySessionId { get; set; } 
    public virtual Session CreatedBySession { get; set; } 
} 

public class Session 
{ 
    public int SessionId { get; set; } 

    [ForeignKey("CurrentApplication")] 
    public int? CurrentApplicationId { get; set; } 
    public virtual VendorApplication CurrentApplication { get; set; } 

    public virtual ICollection<VendorApplication> Applications { get; set; } 
} 

public class MyDataContext: DbContext 
{ 
    public IDbSet<VendorApplication> Applications { get; set; } 
    public IDbSet<Session> Sessions { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Session>().HasMany(x => x.Applications).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId).WillCascadeOnDelete(false); 
     // Note: We have to turn off Cascade delete on Session <-> VendorApplication relationship so that SQL doesn't complain about cyclic cascading deletes 
    } 
} 

セッションは、多くのVendorApplications(Session.Applications)を作成するための責任を負うことができますが、セッションは時間(Session.CurrentApplication)で最も1 VendorApplicationに取り組んでいます。 [ForeignKey(..)]属性ではなく、currentApplicationIdプロパティをModelBuilderのCurrentApplicationナビゲーションプロパティと結びつけたいと思います。あなたは[のForeignKey(..)]を削除すると、私は

を試してみた

物事はCurrentApplicationプロパティはCurrentApplicationId列に結び付けられていないデータベースにCurrentApplication_VendorApplicationId列を生成し属性。

私は明示的に以下のようにCurrentApplicationId列名を使用して関係をマッピングしようとしましたが、データベースのカラム名「CurrentApplicationId」は、既にプロパティSession.CurrentApplicationIdで使用されているため、明らかに、これはエラーを生成します。

modelBuilder.Entity<Session>().HasOptional(x => x.CurrentApplication).WithOptionalDependent().Map(config => config.MapKey("CurrentApplicationId")); 

私がしたいのは[ForeignKey(..)]と同じ操作をモデルビルダー内で実行するので、ここでは非常に明白なものがありません。それとも、これは悪い習慣であり、明示的に除外されたケースですか?

答えて

10

リレーションシップを一対多としてマップし、リレーションシップのコレクションプロパティを省略する必要があります。

modelBuilder.Entity<Session>() 
    .HasOptional(x => x.CurrentApplication) 
    .WithMany() 
    .HasForeignKey(x => x.CurrentApplicationId) 
+1

はい、それです!私は実際にその設定で先に遊んでいましたが、EFは多重度衝突の例外を投げたので、関係は1:1でなければならないと判断しました。もちろん、私はもともとCurrentApplicationIdをnull不可能なものとして持っていたので、多重性の競合が実際に起こったことを認識しています。**(顔の手のひら)**。助けてくれてありがとう、非常に感謝! – Walter

関連する問題