Lydon
Lydon

Reputation: 2975

Joining LINQ results with IEnumerable

I have an API written in .NET 4.5 using Entity Framework. Here is what one of the methods looks like:

private myEntities db = new myEntities();

// GET api/User
public IEnumerable<User> GetUsers()
{
    return from u in db.Users
           select u;
}

Pretty simple. This table can join with a Roles table, so a User can have many Roles. The foreign key UserId is in the Roles table. Here's what I'm trying to do:

private myEntities db = new myEntities();

// GET api/User
public IEnumerable<User> GetUsers()
{
    return from u in db.Users
           join r in db.Roles on u.UserId equals r.UserId
           select new User
           {
               UserId = u.UserId,
               Roles = u.Roles
           };
}

This throws an error: The entity or complex type 'ppadModel.User' cannot be constructed in a LINQ to Entities query

How do I write a query that returns the User and all the Roles associated with that user?

Upvotes: 1

Views: 2419

Answers (1)

Rand Random
Rand Random

Reputation: 7440

You use the .Include extension method.

Like this:

return from u in db.Users.Include("Roles")
select u;

You can also use lamba expression to avoid strings:

return from u in db.Users.Include(x => x.Roles)
select u;

This tells the Entity Framework to load all users and additional all associated roles for the users.

Upvotes: 1

Related Questions