Home > other >  Using Entity Framework with SQL Server many-to-many relations
Using Entity Framework with SQL Server many-to-many relations

Time:06-22

Do not know how to use the advanced features of displaying thing here, so please excuse ;-)

The database structure is

User --> UserOwnerR <-- Owner

Also I have several support structures (ex. addresses belonging to a specific owner).

I need to find all addresses to whom a specific user has access because it belongs to on/many owners, but not addresses to whom the user have a owner relation.

CodePudding user response:

n:m relations can be realized without a join table in EF Core 5 .

public class User
{
    // user properties 
    public IEnumerable<Owner> Owners { get; set; }

}

public class Owner
{
    // owner properties
    public IEnumerable<User> Users { get; set; }
}

CodePudding user response:

You did not specify wether you’re using ef Code first approach (you generated your Schema based on c# classes) or database first approach (generate c# classes from database tables) or none of those (manually set up your entities).

If you are able to change your classes manually, you might add navigation properties. Those might look like this:

public class User
{
    // whatever 
    public IEnumerable<UserOwnerR> userOwners { get; set; }

}

public class Owner
{
    // whatever
    public IEnumerable<UserOwnerR> userOwners { get; set; }

}

public class UserOwnerR
{
    public virtual Owner owner { get; set; }
    public virtual User user { get; set; }
}

Now you are able to place conditions while joining those tables together. Use the sql syntax based query option with linq, as it’s easier to connect your tables that way. You might want to take a look at Entity Framework Join 3 Tables to construct your individual query.

  • Related