Linq-To-Entities Include - entity-framework

I'm currently learning a bit more about Linq-To-Entities - particularly at the moment about eager and lazy loading.
proxy.User.Include("Role").First(u => u.UserId == userId)
This is supposed to load the User, along with any roles that user has. I have a problem, but I also have a question. It's just a simple model created to learn about L2E
I was under the impression that this was designed to make things strongly type - so why do I have to write "Role"? It seems that if I changed the name of the table, then this wouldn't create a compilation error...
My error is this:
The specified type member 'Roles' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
The solution below allows me to now write the code:
proxy.User.Include(u => u.Role).First(u => u.UserId == userId)
Which is MUCH nicer!

Include is a hint to eager load, it does not force eager loading.
Always check the IsLoaded property before referencing something that you hope was eager loaded by Include.
There are ways to put a strongly typed object in the include statement, but there is no solution available to this issue out of the box with Entity Framework. Google something like: Entity Framework ObjectQueryExtension Include

Related

Does Entity Framework load all related entities to unlimited depth when using eager loading

I tried searching but couldn't find an exact answer to this on docs.microsoft at: https://learn.microsoft.com/en-us/ef/core/querying/related-data#eager-loading
I have this bit of code:
await MyDbContext.Users.Where(u => u.Id == Id).Include(u => u.UserContacts).ThenInclude(uC => uC.Contact);
The return type is of type User and Contact is also of type User.
When I debug and step through, it seems like all the Contacts of the required User are loaded, as well as all their Contacts, and then all their Contacts, and so on.
Question:
Is this expected behavior for EF and if so, doesn’t this impact performance, having to look up the DB to such depths?
Is there a way for me to specify a kind of 'max depth'?
The closest match to what I'm asking here that I cam across was probably this SO thread:
How does Entity Framework work with recursive hierarchies? Include() seems not to work with it
You can navigate to entities that your eager loading query doesn't specify in two scenarios:
Navigation Property Fix-UP
If a query, or a previous query on the same DbContext has loaded an Entity that is the target of a Navigation Property, the change tracker will "fix up" the navigation property.
Lazy Loading
Obviously if Lazy Loading is enabled, Navigation Properties will be loaded as you access them.

when using code first, accessing association does not account for .Take(x)

2 entities: Member and Comment
Member has an ICollection<Comment> Comments
Whenever I use member.Comments.Take(x) EF produces a query that gets all the comments from database.
Is it supposed to be like that?
Is it because property is ICollection?
Is there a way to tell EF to factor in my Take(x) or should i refactor my code to use context.Comments.Where(c=>c.MemberId==member.Id).Take(x) and live with it?
As described by #J. Tihon it is how EF works. When accessing lazy loaded property EF will always load the whole collection and any Linq expression is evaluated on the loaded collection. If you want to avoid that you must use the query as you described but the result of the query will not be loaded into your navigation property. To solve this you can use explicit loading instead of lazy loading:
context.Entry(member)
.Collection(m => m.Comments)
.Query()
.OrderBy(...) // Take requires some sorting
.Take(2)
.Load();
This should fill your Comments property with two comments.
The proxy classes generated by EF only provide lazy-loading for navigation properties, but they do not evaluate queries. Once you accessed the member.Comments property, the Comment-entities are loaded from the database and your query is applied in memory. To avoid this, you must get your comments in a query that is directly executed on the object-set (like the example you've already gave).
I believe this is by design, since you would have to return an IQueryable from the navigation property in order for the EF to intercept access to this property, but I suppose this isn't covered aswell.
You've already described a way to handle this, although it isn't pretty. Another option would be to somehow tell EF to partially load the property when you make the original query for the Member-object. I will look into that, but I can already think of one or two thinks that might go wrong with that approach.
Edit
After some research and trial and error I couldn't come up with another approach, that could be executed directly on the DbSet<Member> rather than DbSet<Comment> and returns a Member object. I is possible using an anonymous object:
var query = from m in catalog.Members
select new
{
Id = m.Id,
Name = m.Name,
Comments = m.Comments.Take(1)
};
Which could then be translated into a Member-object in memory, but of course it wouldn't be connected to the context in anyway (=no change tracking). In the sample query above I cannot create an instance of Member instead of an anonymous type, because EF can only create non-complex types (I'm guessing because the context knows that "Member" is an entity).

Using Entity Framework navigation properties without creating lots of queries (avoiding N+1)

I've been using Entity Framework Profiler to test my data access in an MVC project and have come accross several pages where I'm making far more db queries than I need to because of N+1 problems.
Here is a simple example to show my problem:
var club = this.ActiveClub; // ActiveClub uses code similar to context.Clubs.First()
var members = club.Members.ToList();
return View("MembersWithAddress", members);
The view loops through Members and then follows a navigion property on each member to also show their address. Each of the address requests results in an extra db query.
One way to solve this would be to use Include to make sure the extra tables I need are queried up front. However, I only seem to be able to do this on the ObjectSet of Clubs attached directly to the context. In this case the ActiveClub property is shared by lots of controllers and I don't always want to query the Member and address table up front.
I'd like to be able to use something like:
var members = club.Members.Include("Address").ToList();
But, Members is an EntityCollection and that doesn't have the Include method on it.
Is there a way to force a load on the Members EntityCollection and ask EF to also load their Addresses?
Or, is using EntityCollection navigation properties on an entity in this way, just a really bad idea; and you should know what you're loading when you get it from the context?
If your entities inherits from EntityObject try to use this:
var members = club.Members.CreateSourceQuery()
.Include("Address")
.ToList();
If you use POCOs with lazy loading proxies try to use this:
var members = ((EntityCollection<Club>)club.Members).CreateSourceQuery()
.Include("Address")
.ToList();
Obviously second version is not very nice because POCOs are used to remove dependency on EF but now you need to convert the collection to EF class. Another problem is that the query will be executed twice. Lazy loading will trigger for Members once to access the property and then second query will be executed when you call ToList. This can be solved by turning off lazy loading prior to running the query.
When you say ActiveClub is shared I believe it means something like it is property in base controller used in derived controllers. In such case you can still use different code in different controller to fill the property.

Is projecting lazy, eager or explicit in entity framework?

I've learned about lazy loading, eager loading with .include and explicit loading with .load(), but something that confuses me is when you project in a query and explicitly request a navigation property like this:
var address = from a in context.Addresses
select {a, Name = a.Contact.Name}
Here Contact is a navigation property in Addresses that links to a Contact entity.
I tried with both lazy loading on and off and it works both ways. I wonder when I request my data like this, am I eager loading or deferred loading? My understanding that only one query will be made to the database which means it's eager loading, except in this case only the "Name" property of the Contact entity will be loaded, as opposed to the entire Contact entity if I were to use context.Addresses.include("Contact")? Does it make a query like this more efficient than eager loading with .include() ?
Some clarifications will be appreciated.
Lazy loading, eager loading and explicit loading works in the most common scenarios. Projection is replacement for eager loading because it can also load related entities with single query. Using projection make sense if you need to load entities with some complex query because eager loading doesn't work in these cases. Use projection if you need:
Any kind of join or aggregation in the linq query. As I know Include is ignored once you start using manual joins.
Any kind of filtering or sorting in navigation property. Include can only load all related entities from navigation property without any sorting. Once you need to apply any where condition or order by on related entities you can't use Include and you must use projection.
It's lazy evaulation as it won't execute until something enumerates over address.
Eager loading is normally used to describe an entity object's navigation properties being pre-loaded but in this case you are not directly materializing any entity objects as you are projecting onto an anonymous type.
If you access a.Contact.Name rather than Name you'll most likely cause another database hit as you haven't eager loaded the Contact object of Address, you specifically selected and projected the Name property onto an anonymous object.

Finding Entity Framework contexts

Through various questions I have asked here and other forums, I have come to the conclusion that I have no idea what I'm doing when it comes to the generated entity context objects in Entity Framework.
As background, I have a ton of experience using LLBLGen Pro, and Entity Framework is about three weeks old to me.
Lets say I have a context called "myContext". There is a table/entity called Employee in my model, so I now have a myContext.Employees. I assume this to mean that this property represents the set of Employee entities in my context. However, I assume wrong, as I can add a new entity to the context with:
myContext.Employees.AddObject(new Employee());
and this new Employee entity appears nowhere in myContext.Employees. From what I gather, the only way to find this newly added entity is to track it down hiding in the myContext.ObjectStateManager. This sounds to me like the myContext.Employees set is in fact not the set of Employee entities in the context, but rather some kind of representation of the Employee entities that exist in the database.
To add further to this confusion, Lets say I am looking at a single Employee entity. There is a Project entity that has a M:1 relationship with Employee (an employee can have multiple projects). If I want to add a new project to a particular employee, I just do:
myEmployee.Projects.Add(new Project());
Great, this actually adds the Project to the collection as I would expect. But this flies right in the face of how the ObjectSet properties off of the context work. If I add a new Project to the context with:
myContext.Projects.AddObject(new Project());
this does not alter the Projects set.
I would appreciate it very much if someone were to explain this to me. Also, I really want a collection of all the Employees (or Projects) in the context, and I want it available as a property of the context. Is this possible with EF?
An ObjectSet is a query. Like everything in LINQ, it's lazy. It does nothing until you either enumerate it or call a method like .Count(), at which point a database query is run, and any returned entities are merged with those already in the context.
So you can do something like:
var activeEmployees = Context.Employees.Where(e => e.IsActive)
...without running a query.
You can further compose this:
var orderedEmployees = activeEmployees.OrderBy(e => e.Name);
...again, without running a query.
But if you look into the set:
var first = orderedEmployees.First();
...then a DB query is run. This is common to all LINQ.
If you want to enumerate entities already in the context, you need to look towards the ObjectStateManager, instead. So for Employees, you can do:
var states = EntityState.Added || EntityState.Deleted || // whatever you need
var emps = Context.ObjectStateManager.GetObjectStateEntries(states)
.Select(e => e.Entity)
.OfType<Employee>();
Note that although this works, it is not a way that I would recommend working. Typically, you do not want your ObjectContexts to be long-lived. For this, and other reasons, they are not really suitable to be a general-purpose container of objects. Use the usual List types for that. It is more accurate to think of an ObjectContext as a unit of work. Typically, in a unit of work you already know which instances you are working with.