开发者

Double self-referencing property with Entity Framework

开发者 https://www.devze.com 2023-02-21 02:14 出处:网络
This code represents in small scale my problem: public class Person { public int ID { get; set; } public string Name { get; set; }

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 diffe开发者_开发技巧rent 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


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

精彩评论

暂无评论...
验证码 换一张
取 消