Nindalf
Nindalf

Reputation: 59

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.

Upvotes: 0

Views: 103

Answers (2)

Nindalf
Nindalf

Reputation: 59

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

Upvotes: 0

Selom
Selom

Reputation: 402

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.

Upvotes: 1

Related Questions