dom
dom

Reputation: 6832

Entity Framework 4.1 two FKs pointing to same table

I ran into an issue when adding two navigation properties of the same type in a model, giving me this error :

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

This is the code (broken) that I have :

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

And this is what the relationships look like in the database.

database relationships

I've read about [InverseProperty], but I'm not sure how I would go about implementing that in my situation. Do I need to add reverse navigation properties in my Utilisateur class to make this work?

Upvotes: 0

Views: 480

Answers (1)

dom
dom

Reputation: 6832

Shortly after asking I realized my mistake, this is how I fixed it :

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

Upvotes: 2

Related Questions