2
我首先使用实体框架代码。我有2个实体(用户和配置文件),它们之间的关系是一对多的,即一个用户只能有一个配置文件,但一个配置文件可以分配给多个用户。下面的实体:带有一对多关系的EF 4.1代码首先创建重复的外键
[Table("Users")]
public class User
{
[Key(), Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public virtual string Name { get; set; }
[Required]
[ForeignKey("Profile")]
public virtual int ProfileId { get; set; }
public virtual Profile Profile { get; set; }
public virtual ICollection<AnotherEntityB> anotherEntityB { get; set; }
}
[Table("Profiles")]
public class Profile
{
[Key(), Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public virtual string Name { get; set; }
// Below the user that performs the discharge of the profile. Only 1 user can do it.
[ForeignKey("User")]
public virtual int? UserId { get; set; }
public virtual User User { get; set; }
public virtual DateTime? dischargeDate { get; set; } <-- this is the date that user performs the discharge of the profile
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<AnotherEntityC> anotherEntityC { get; set; }
}
还我已删除的OnModelCreating方法的一些约定:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
的问题是,EF英孚教育创造用户实体两个外键:
ProfileId (FK, int, No NULL)
Profile_Id (FK, int, NULL)
并且只有一个外键应该位于Users实体中: ProfileId(FK,int,No NULL)
怎么了?
它就像一个魅力!非常感谢!该工作原理的另一种方法是通过重写OnModelCreating并把这样的:modelBuilder.Entity() .HasRequired(R => r.Profile) .WithMany(S => s.Users) .HasForeignKey(F => f.ProfileId ) .WillCascadeOnDelete(false); –
user1624552
@ user1624552:是的,这是Fluent版本。我以为你正在使用注释,因为你的模型中已经有了一些属性。但是如果你想禁用级联删除,你甚至必须**使用Fluent版本。我的答案中的属性配置将对应于所需关系的默认值,即'WillCascadeOnDelete(true)'。 – Slauma