EF 4.1 Code First ModelBuilder HasForeignKey for One-to-One Relationships

Very simple, I first use the Entity Framework 4.1 code, and I would like to replace my [ForeignKey (..)] attributes with free calls on modelBuilder. Something similar to WithRequired (..) and HasForeignKey (..) below, which bind the explicit foreign key property (CreatedBySessionId) along with the corresponding navigation property (CreatedBySession). But I would like to do this for one single relationship, and not one for many:

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

The following is a more specific example. This works quite successfully with the [ForeignKey (..)] attribute, but I would like to end this and configure it exclusively on 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), VendorApplication (Session.CurrentApplication). CurrentApplicationId NavigationAutribate ModelBuilder [ForeignKey (..)].

,

[ForeignKey (..)] CurrentApplication CurrentApplication_VendorApplicationId , CurrentApplicationId.

, CurrentApplicationId, , , , , "CurrentApplicationId" Session.CurrentApplicationId:

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

, - , , , , [ForeignKey (..)], . , ?

+5
1

" " .

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

All Articles