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.
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()
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With