2

I am using entity framework code first. I have 2 entities (Users and Profile) and the relationship between them is one-to-many, that is, one user can only have one profile, but one profile can be assigned to many users. Below the entities:

[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; }
}

also I have removed some conventions in the OnModelCreating method:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

The problem is that EF is creating two foreign keys in user entity:

ProfileId (FK, int, No NULL)
Profile_Id (FK, int, NULL)

and only one foreign key should be in Users entity: ProfileId (FK, int, No NULL)

What's wrong?

4

1 回答 1

5

因为有两个导航属性User,并且引用实体 EF 不能通过约定来决定这两个属性中的哪一个属于 entity 中的Users逆属性。您必须 EF 使用该属性给出提示:ProfileUserProfileUser[InverseProperty]

[InverseProperty("Users")]
public virtual Profile Profile { get; set; }

现在,它定义User.Profile是 的反向导航属性,Profile.Users并且两者都是相同关系的末端。没有属性 EF 假定这两个导航属性是两个不同关系的结束,其中一个负责附加外键Profile_Id

这里有一点背景。

于 2013-05-20T21:52:50.543 回答