ef core shared child table with one-to-many

363 Views Asked by At

I would like to have a shared table that can be somehow referenced to multiple parent tables. The parent tables can have multiple rows from the shared Attachement table. The Type/TypeId would be a column which points to the parent table (like if the parentId is in Person or Company table) Shared table:

Id   | ParentId   | Type/TypeId   |   Value
1         1            Person/1    "somestringvalue"
2         1            Person/1    "another value"
3         3            Company/2   "value"
....

The models would look something like this

public class Attachement
{
    [Key]
    public int Id { get; set; }
    //PK- Id of the parent table
    public int ParentId { get; set; }
    // type or enum of a parent table. Should point to which table it points to
    public int Type { get; set; }

    public string Value { get; set; }
}

public class Person
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    //shared table
    public ICollection<Attachement> Attachements { get; set; }
}

public class Company
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    //shared table
    public ICollection<Attachement> Attachements { get; set; }
}

Sidenote also - im using code first pattern.

Thanks!

0

There are 0 best solutions below