简体   繁体   中英

EF code first, child holds a list of parent objects

I have a nasty problem with EF code first where I need some help. I have a Student which inherit from Person . The Student can have friends like the Worker which inherit also from person.

class Person
{
    public int Id { get; set; }
    //...
}

class Student : Person
{
    public virtual List<Person> Friends { get; set; }
    //...
}

class Worker : Person
{
    //there are other classes like this one
}

This is the exception I get if I try to write the entities to my sqlite DB:

The member with identity 'PersonSelf' does not exist in the metadata collection.

If I change the list for example to Worker it is working but not with Person . What can I change to solve this? Thank you for your help.

You should not have any problem If you have defined your models and db context well I think. I have created a small repo on github to test your models. Here is the link github repo My models are very very simple:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}
public class Student : Person
{
    public Student()
    {
        Friends=new List<Person>();
    }
    public virtual List<Person> Friends { get; set; }
    public int StudentAge { get; set; }
}
public class Worker : Person
{
    public decimal WorkerSalary { get; set; }
}

I'm using DotNet Core and I was able to create database and insert data.

Please check the repo and let me know If it works for you.

Thank you for the hints. To solve this problem, you need to tell EF to create a mapping table in the DB. The reason is because it is a matter of a “Many to Many” problem.

Please consider also my other post .

    public class ModelConfiguration
    {
        private static void ConfigureGridDataCollectionEntity(DbModelBuilder modelBuilder)
        {
            // Student
            modelBuilder.Entity<Student>()
                .HasMany(p => p.Friends)
                .WithMany()
                .Map(cs =>
                {
                    cs.MapLeftKey("StudentId");
                    cs.MapRightKey("FriendsId");
                    cs.ToTable("StudentFriend");
                });
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM