akd
akd

Reputation: 6758

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?

Upvotes: 0

Views: 104

Answers (2)

Markus
Markus

Reputation: 22456

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

Upvotes: 1

kimbaudi
kimbaudi

Reputation: 15555

In your Student model, you are saying there is a one-to-many relationship between Student and Picture. Same thing with your School model. So EF adds a foreign key to Picture for both Student and School model. That is the expected behavior.

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

Based on your Student and School model, I expect EF to add 2 foreign keys to Picture (StudentId and SchoolId). How should it look to you?

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

If you create another model that contains ICollection <Picture> Pictures { get; set; } as a property, then yes, that would create another foreign key in Picture. But if you omit it, it won't.

I'm not sure what you are expecting. Can you elaborate?

Upvotes: 0

Related Questions