Configure Related Entities on modelBuilder instead on Include method - entity-framework

Guys it is possible configure on modelBuilder to set which Entities get related entities instead i use Include method on my LINQ queries?
PROS: I don't need to use Include Method on queries provided by my IRepository Interface, nor reference EntityFramework.dll

No it is not possible. You must either use eager loading, lazy loading or explicitly load each relation:
Eager loading - calling Include. This will load relation during initial query in single database roundtrip.
Lazy loading - making navigation properties virtual. This will load each navigation property when the property is first used by your code. It creates separate database roundtrip for each navigation property.
Explicit loading - you will manually tell property to load (the approach depends on used API - DbContext x ObjectContext). Again this will create separate roundtrip for each navigation property.

Related

Enable Lazy Loading on AfterSaveEntities using Breeze

I'm using breeze with EF6 and EFContextProvider.
On save changes I'm using :
{ TransactionType = TransactionType.TransactionScope };
I'd like to use lazy loading for validating my entities easier during the AfterSaveEntities delegate but I can't do that. Trying to set LazyLoadingEnabled = false during the transaction doesn't work. Entities still don't load relations when needed.
Is there any way to do that?
No, you'll need to load the entities manually. In fact, as explained in this SO answer, you should create a separate EF context for loading any additional entities.
When the SaveResult is sent back to the client, any additional entities that are attached via navigation properties will be serialized along with the original entities. So you should keep the original context clean unless this is your intent.

Eagerly load all entities in DbContext

Is there a way to configure a DbContext to eagerly load all of its entities? we have attempted:
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
We tried both with and without ProxyCreationEnabled being turned off.
I just happen to know that the DB we are loading in is not very large, doesn't change very often, and is referenced a lot. So keeping it all in memory will be very advantageous.
No, LazyLoadingEnabled disabled does not mean "EagerLoadingEnabled". It is: "not even lazy loading enabled, only loading explicitly requested by you". An EF context will never automatically do eager loading. Just think what could happen with many associations between entities and large databases.
You won't benefit much from pre-loading everything into your context unless you use methods to access the local entities only. You can access local entities by DbSet.Local or DbSet.Find.
Just accessing a DbSet (like context.Customers) will execute a database query anyway. If lazy loading is disabled it may use local entities for navigation properties (called relationship fixup) but otherwise accessing navigation properties will also cause database queries.
It sounds like you should populate an object graph from your database, using a context, and cache it outside the context. Note that if you fetch the data read-only you may want to use the AsNoTracking extension method. (Like context.Customers.AsNoTracking()).
Nope... but if you're looking for the most performant way to load bulk data into EF DbContext, I recommend writing a stored procedure that returns multiple result sets (one for each entity type). EF will automatically hook up the nav properties when the entities are loaded into the context.
Here's instruction on how to do it from both the DB first and code first perspectives:
http://msdn.microsoft.com/en-us/data/jj691402.aspx

Entity Framework - Removing virtual keyword from navigation properties

I am using entity framework with database first approach, along with EF 4.x DBContext Generator. All my entity classes have navigation properties which are marked as "virtual". I want to remove virtual keyword from all my entity classes. There are around 350 entity classes
You must modify T4 template (.tt) file to remove virtual keyword.
Removing virtual will mean that you are unable to use lazy loading for entity framework. In my opinion lazy loading has a very limited scope and is mostly misused (which often causes performance issues). However do note that when you turn it off you may need to adjust your code to manually load additional navigation properties when you retrieve data. You can do this by using .Include in your EF query
To remove the virtual flag you probably need to disable lazy loading in your EF generator.
You may want to try this VS extension, It adds (among other things) fine control over the virtual modifier:
EF Designer Extender

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.