如何在多个关系中使用NOT NULL设置外键属性

时间:2012-02-20 09:47:34

标签: entity-framework entity-framework-4 entity-framework-4.1

我有两个实体

public class User
{
        [Key]
        public int Id { get; set; } // PK

        // for many-to-many relation with Booking.Members
        public virtual ICollection<Booking> Bookings { get; set; }
}

public class Booking
{
        public Booking()
        {
            Members = new List<User>();
        }

        public int Id { get; set; } // PK

        [ForeignKey("UserByCreated")]
        public int UserByCreatedId { get; set; } // FK
        public virtual User UserByCreated { get; set; } 

        // for many-to-many relation with User.Bookings
        public virtual ICollection<User> Members { get; set; }

}

如上所示,用户和预订有两种不同的关系,一种是多对多关系,另一种是外键关系。

我想要做的是在Bookings表中使用带有NOT NULL条件的UserByCreatedId外键列。

然而,由于与User的另一种关系,似乎不可能。 对此有什么解决方案吗?

1 个答案:

答案 0 :(得分:2)

使用Fluent API配置关系,因为当两个实体之间存在多个关系时,EF无法识别关系。

修改

UserByCreated关系需要更改为可选,以避免多个删除路径问题。

public class Booking
{
        public Booking()
        {
            Members = new List<User>();
        }

        public int Id { get; set; } // PK

        [ForeignKey("UserByCreated")]
        public int? UserByCreatedId { get; set; } // FK

        public virtual User UserByCreated { get; set; } 

        public virtual ICollection<User> Members { get; set; }    
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().HasMany(u => u.Bookings)
         .WithMany(b => b.Members);
    modelBuilder.Entity<Booking>().HasOptional(u => u.UserByCreated)
         .WithMany()
         .HasForeignKey(b => b.UserByCreatedId)
         .WillCascadeOnDelete(false);
}