Search code examples
c#t-sqlentity-framework-core

Linking entities in EF Core


I am looking for a way to link tables as entities in EF Core 6.0 (Or if 8.0 is required for a better solution I am open to that as well.)

My tables are as follows:

CREATE TABLE Groups
(
   Id           INT IDENTITY PRIMARY KEY ,
   ResourceType NVARCHAR(20)     NOT NULL ,
   Name         NVARCHAR(100)    NOT NULL ,
   CompanyGuid  UNIQUEIDENTIFIER NOT NULL
)

CREATE TABLE GroupMembers
(
   Id       INT IDENTITY PRIMARY KEY ,
   GroupId  INT NOT NULL
      REFERENCES Groups ,
   MemberId INT NOT NULL
)

And my Group entity:

public class Group
{
    public string ResourceType { get; set; }
    public string Name { get; set; }
    public List<int> Members { get; set; }
    public Guid CompanyGuid { get; set; }
}

I want to avoid making a GroupMembers entity and having the Id's in the list of memberId's in the Group entity.

The difficult part is that there are different types of members, which one is specified in ResourceType. This makes me unable to just have it as List<Member> Members.

Elaborating on different member types. The different member types, each having their own table.

The types of members are "Users", "Vehicle" and "Equipment". They are obviously very different, and will never be in a group across types, the only thing they have in common is the Id's, as they are generated by the database.

The memberId will always reference a single table, but what table might differ from row to row.

The system is constructed in bad way, only using EF core to access and interact with the database. The actual creation of tables and such is done using DbUp, a choice made before I got hired, and I am not allowed to change...


Solution

  • If you have a many-to-many relationship you don´t need to model the connection table.

    Just do:

    public class Group
    {
        public int Id { get; set; }
        public List<Users> Members { get; set; }
        ...
    }
    
    public class User
    {
        public int Id { get; set; }
        public List<Group> Groups { get; set; }
        ...
    }
    

    You cannot have a List<int> only for the Ids. You need proper Navigation Properties.