实体框架4.1两个FK指向同一个表

时间:2011-11-10 17:03:36

标签: entity-framework-4.1

在模型中添加两​​个相同类型的导航属性时遇到了一个问题,给我这个错误:

System.Data.SqlClient.SqlException: 
Invalid column name : 'Createur_IdUtilisateur'.
Invalid column name : 'Proprietaire_IdUtilisateur'.

这是我的代码(破碎):

public class Billet
{
    [Key]
    public int IdBillet { get; set; }
    public int IdMandat { get; set; }
    public string Titre { get; set; }
    [AllowHtml]
    public string Description { get; set; }
    public int IdUtilisateurCreateur { get; set; }
    public int IdUtilisateurProprietaire { get; set; }
    public DateTime DateCreation { get; set; }
    public DateTime? DateFermeture { get; set; }
    public int EstimationTemps { get; set; }
    public int Priorite { get; set; }
    public bool FermetureParCreateur { get; set; }

    public virtual ICollection<Intervention> Interventions { get; set; }
    public virtual Mandat Mandat { get; set; }
    public virtual Utilisateur Createur { get; set; }
    public virtual Utilisateur Proprietaire { get; set; }
}

public class Utilisateur
{
    [Key]
    public int IdUtilisateur { get; set; }
    public int IdUtilisateurRole { get; set; }
    public string Courriel { get; set; }
    public string Nom { get; set; }
    public string Password { get; set; }
    public bool Actif { get; set; }

    public virtual UtilisateurRole Role { get; set; }
}

这就是数据库中关系的样子。

database relationships

我读过[InverseProperty],但我不确定如何在我的情况下实现这一点。我是否需要在 Utilisateur 类中添加反向导航属性才能使其正常工作?

1 个答案:

答案 0 :(得分:2)

在询问后我意识到自己的错误,这就是我修复它的方法:

public class Entities : DbContext
{
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        ...

        modelBuilder.Entity<Billet>()
            .HasRequired(b => b.Createur)
            .WithMany()
            .HasForeignKey(b => b.IdUtilisateurCreateur);
        modelBuilder.Entity<Billet>()
            .HasRequired(b => b.Proprietaire)
            .WithMany()
            .HasForeignKey(b => b.IdUtilisateurProprietaire);
    }
}