akd akd - 4 days ago 5
C# Question

How to Model One to Many relationship pointing to same entity from different entities in EF

I have an entity as Student

public class Student{

..

public ICollection<Picture> Pictures {get;set;}


}

And School entity

public class School{

..

public ICollection<Picture> Pictures {get;set;}
}


When I create this model and run the migrations I can see that in Pictures table in the database 2 foreign key properties have been created as StudentId and SchoolId.

It doesn't look right to me to have those foreign keys in the Pictures table.

In the future if another entity needs to have list of Pictures then which means another foreign key property in the Pictures table.

How can I change this behavior in the code first model? Or this is the correct approach?

Answer

If a picture cannot be shared among a school and a student, you could create separate entities for the two picture types. The best way to do this is to create a base class and derived classes for each specific picture type:

public abstract class Picture 
{
    public int Id { get; set; }
    // ...
}
public class SchoolPicture : Picture
{
    // ...
}
public class StudentPicture : Picture
{
    // ...
}

Then the School entity references the SchoolPicture and the Student entity references the StudentPicture:

public class School
{
    // ...
    public virtual ICollection<SchoolPicture> Pictures {get;set;}
}
public class Student
{
    // ...
    public virtual ICollection<StudentPicture> Pictures {get;set;}
}

This way, two separate tables are created for the pictures with only a single foreign key to the corresponding parent entity:

Created model

Comments