Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double self-referencing property with Entity Framework

This code represents in small scale my problem:

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Person Parent { get; set; }
    public virtual ICollection<Person> Friends { get; set; }
}

When I use this class in an Entity Framework (4.1) scenario, the system generates one only relation, thinking that Parent and Friends are the two faces of the same relation.

How can I tell to semantically separate the properties, and generate two different relations in SQL Server (since we can see that Friends are totally different from Parents :-)).

I tried with the fluent interfaces, but I think I don't know the right calls to do.

Thanks to all.

Andrea Bioli

like image 730
Andrea Avatar asked Apr 01 '11 13:04

Andrea


1 Answers

You could use this in the Fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>()
        .HasMany(p => p.Friends)
        .WithOptional()
        .Map(conf => conf.MapKey("FriendID"));

    modelBuilder.Entity<Person>()
        .HasOptional(p => p.Parent)
        .WithMany()
        .Map(conf => conf.MapKey("ParentID"));
}

I am assuming here that the relationships are optional. The People table gets two foreign keys FriendID and ParentID now. Something like this should work then:

using (var context = new MyContext())
{
    Person person = new Person() { Name = "Spock", Friends = new List<Person>()};
    Person parent = new Person() { Name = "Sarek" };
    Person friend1 = new Person() { Name = "Kirk" };
    Person friend2 = new Person() { Name = "McCoy" };

    person.Parent = parent;
    person.Friends.Add(friend1);
    person.Friends.Add(friend2);

    context.People.Add(person);

    context.SaveChanges();

    // Load with eager loading in this example
    var personReloaded = context.People
        .Where(p => p.Name == "Spock")
        .Include(p => p.Parent)
        .Include(p => p.Friends)
        .First();
}
like image 152
Slauma Avatar answered Oct 17 '22 02:10

Slauma