最初にエンティティ フレームワーク コードを使用しています。2 つのエンティティ (ユーザーとプロファイル) があり、それらの間の関係は 1 対多です。つまり、1 人のユーザーは 1 つのプロファイルしか持つことができませんが、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 がユーザー エンティティに 2 つの外部キーを作成していることです。
ProfileId (FK, int, No NULL)
Profile_Id (FK, int, NULL)
また、Users エンティティには外部キーを 1 つだけ含める必要があります: ProfileId (FK, int, No NULL)
どうしたの?