5

非常に単純に、最初にEntity Framework 4.1コードを使用しており、代わりに[ForeignKey(..)]属性をmodelBuilderでの流暢な呼び出しに置き換えたいと思います。WithRequired(..)およびHasForeignKey(..)に似たもので、明示的な外部キープロパティ(CreatedBySessionId)を関連するナビゲーションプロパティ(CreatedBySession)と結び付けます。しかし、私はこれを1対多ではなく1対1の関係に対して行いたいと思います。

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

より具体的な例を以下に示します。これは[ForeignKey(..)]属性で非常にうまく機能しますが、これを廃止して、純粋にmodelbuilderで構成したいと思います。

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は一度に最大1つのVendorApplication(Session.CurrentApplication)で動作します。[ForeignKey(..)]属性ではなく、ModelBuilderのCurrentApplicationIdプロパティをCurrentApplicationナビゲーションプロパティに関連付けたいと思います。

私が試したこと

[ForeignKey(..)]属性を削除すると、CurrentApplicationプロパティは、CurrentApplicationId列に関連付けられていないCurrentApplication_VendorApplicationId列をデータベースに生成します。

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

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

[ForeignKey(..)]と同じ操作をモデルビルダー内で実行するだけなので、ここでは非常に明白な何かが欠けているように感じます。それとも、これは悪い習慣であり、明示的に除外された場合ですか?

4

1 に答える 1

10

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

modelBuilder.Entity<Session>()
   .HasOptional(x => x.CurrentApplication)
   .WithMany()
   .HasForeignKey(x => x.CurrentApplicationId)
于 2012-07-14T01:10:20.543 に答える