Fluent API one to one relationship mapping

145 views Asked by At

I am trying to make a "One to one" association using the Fluent API. Here are my classes :

public class Person
{
    public Guid Id { get; set; }
    public Guid ProfilId { get; set; }

    public DateTime InsertDate { get; set; }
    public DateTime UpdateDate { get; set; }

    public virtual Profil Profil { get; set; }
}

public class Profil
{
    public Guid Id { get; set; }

    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public String Email { get; set; }

    public virtual Person Person { get; set; }
}

public class PersonMap : EntityTypeConfiguration<Person>  
{
    public PersonMap()
    {

        ...

        ToTable("Person");

        HasRequired(t => t.Profil)
              .WithOptional(c => c.Person)
              .Map(m => m.MapKey("ProfilId")); 
    }  
}

This implementation throws an exception Invalid column name 'ProfilId'.

Would somebody tell me how to set up a mapping with 1-1 relationship using these classes?

Thank you

1

There are 1 answers

2
ocuenca On BEST ANSWER

When configuring one-to-one relationships,Entity Framework requires that the primary key of the dependent also be the foreign key, so you can map the relationship using Data Annotations as follow:

public class Person
{
    [Key]
    [ForeignKey("Profil")]
    public Guid ProfilId { get; set; }

    public DateTime InsertDate { get; set; }
    public DateTime UpdateDate { get; set; }

    public virtual Profil Profil { get; set; }
}

Or using Fluent Api:

  HasKey(t=>t.ProfilId);
  HasRequired(t => t.Profil).WithOptional(c => c.Person);

Edit 1:

Well, EF lets you create an one-to-one relationship between two entities with their own PKs, but you can't use a FK property, so, remove ProfileId in Person entity and configure the relationship this way:

HasRequired(t => t.Profil).WithOptional(c => c.Person);

The MapKey method is used to change the foreign key name in the database, but you can't have a property with the same name in your entity, otherwise, an exception will be thrown.