Linq to SQL - SQL join statement with specific return

36 views Asked by At

I have the following table entity with my sql-database :

using System.Data.Linq.Mapping;

[Table(Name = "Users")]
class Users
{
    [Column(Name="UserKey", IsPrimaryKey=true)]
    public string UserKey { get; set; }
    [Column(Name="Username")]
    public string UserName { get; set; }

    public IList<T_UsersRoles> Roles = new List<UsersRoles>();
}

[Table(Name ="Roles")]
class UsersRoles
{
    [Column(Name="UserKey", IsPrimaryKey =true)]
    public string UserKey { get; set; }
    [Column(Name ="RoleKey", IsPrimaryKey =true)]
    public string RoleKey { get; set; }
}

the only member which is not part of my database is the public IList<T_UsersRoles> Roles = new List<UsersRoles>(); in class Users

I now want just a single SQL-Transaction and have a filled class Users object with a filled list of all roles the user has.

How is this possible?

I already made a join select on both table with an anonymous object new {user, role} but that is not what i want to get back

And i already made this. But here are too many sql-transactions (amount of user +1)

var users = from user in dataContext.GetTable<Users>()               
                where user.Id == "1234" | user.Id == "5678"
                select user;

foreach (var user in users)
{
    user.Roles = (from roles in dataContext.GetTable<UsersRoles>() where roles.Id == user.Id select roles).ToList<UsersRoles>();
    
    Console.WriteLine(user.Id + " " + user.UserName + ":");
    foreach (var role in user.Roles)
    {
        Console.WriteLine("- " + role.RoleKey);
    }
}```
0

There are 0 answers