c# - LINQ many to many relationship - get a list of grouped objects -


i have bit of complicated 1 (for me anyway):

i have 2 entities in many many relationship.

projects       {project_id, projectname} users          {user_id, username}  projects-users {id, project_id, user_id}    

a project can assigned more users.

now want retrieve list of projects (listed once) project_id, name, listofassignedusers:

id  projectname  users 1   project1     u1, u2, u3 2   project2      3   project3     u1 

i can in sql, can't figure out how in linq!

it's linq entity - framework(db first):
classes this:

public partial class projects { public projects() { this.users = new hashset(); }

    public int project_id { get; set; }     public string name { get; set; }      public virtual icollection<users> users { get; set; } } 

public partial class users { public users() { this.projects = new hashset(); }

    public int user_id { get; set; }     public string username { get; set; }      public virtual icollection<projects> projects { get; set; } } 

(i made change removing id projects-users , made combo (project_id, user_id) primary key of that.

remove id field project-users table. primary key if need 1 should {project_id,user_id}. there should (if not already) foreign key constraint between projects.project_id , project-users.project_id , fk between users.user_id , project-users.user_id

if have model mapped in entity framework, reference this:

var result=context.project.include(p=>p.users); 

you can dump results this:

foreach(var record in result) {   console.writeline("{0} {1} {2}",     record.project_id,     record.projectname,     string.join(",",record.users.select(u=>u.username))); } 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -