Dual self-reference property with Entity Framework

This code is a small issue:

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) script, the system generates one single relationship, assuming that the parent and friends are two faces of the same relationship.

How can I say to semantically separate properties and generate two different relationships in SQL Server (since we see that Friends are completely different from their parents :-)).

I tried with smooth interfaces, but I think I don’t know how to call correctly.

Thanks to everyone.

Andrea Bioli

+5
source share
1 answer

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

, . People FriendID ParentID. - :

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();
}
+6

All Articles