Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an entity that is a query of multiple tables

I have a web service that uses the Entity Framework for storage and exposes a public API for CRUD operations.

If I have an entity such as User which has a 1 to many relationship with a Car entity, how do I easily return in my web service method of GetUser(int userId) a instance of user that looks like this:

public class User{
  string Id;
  IEnumberable<Car> Cars;
}

Does this work by default within the entity framework, because I assume that the Cars property is lazy when using it on the server side.

like image 438
the_tokenizer Avatar asked Oct 11 '22 16:10

the_tokenizer


2 Answers

Entity objects are serializable and you will automatically get the Cars property.

However, depending on your LINQ query the Cars property may or may not have been loaded. If you always want to load the Cars property within your given web method, then you should explicitly load the property. Below are a few ways to guarantee you load the Cars property.

1) use the Include("Cars") method in your LINQ query.

2) use projection.

3) Explicitly load the Cars property on an instance of a User object. For example,

userA.Cars.Load()
like image 182
ChrisNel52 Avatar answered Nov 03 '22 00:11

ChrisNel52


First of all you should [Include] Cars at the metadata definition of User entity. Also you probably need to rewrite the getUsers() method to fill the cars. Something like this.

public IQueryable<User> GetUsers()
{
    return this.ObjectContext.User.Include("Cars");
}

It's not easy to explain shortly, i recommend you to visit this, and this web sites.

Hope helps!

like image 20
Morvader Avatar answered Nov 02 '22 23:11

Morvader