I'm using AutoMapper as an ORM in application with Entity Framework v6.
My problem statement is that if I executes a single query via LINQ to Entities on any single entity and maps entity data via AutoMapper with DTO, many other queries will be executed at the same time while data binding.
Kindly anyone let me know, how to avoid this problem.
This is expected behavior. Remember, AutoMapper just looks at the destination type and will map matching properties from the source type. If you don't want some properties to be mapped lazily, you have several options:
Remove the properties from the destination model
Use Include to eagerly fetch properties
Use LINQ projection in AutoMapper (ProjectTo) to force EF to use the Select LINQ projection to grab whatever data it needs to based on the source type
I think this may happens due to the lazy loading enabled.
Read this answer :
Is automapper preventing lazy loading with EF?
Related
So, I'm using EF DbContexts in the following way. One AppDbContext is an abstract class derived from DbContext, it contains my DbSets and is used as a type to inject into services. Its "implementation" is like AppDbContextMySql, which is self-explanatory - it's derived from AppDbContext and handles the connection to the actual DB. There can be several such abstract/implementation pairs to separate the data tables, but usually, all of them point to the same actual DB instance.
Then I need to migrate it all, so I add a MigrationDbContext implementing all the datasets and all the entity configurations needed, namely composite primary keys which can only be configured in OnModelCreating override.
The question is, if I already have the data model configuration in MigrationDbContext, have applied the migration successfully to the DB, and it's DB's job to handle keys and indexes anyway, do I need to have the model configuration in my actually consumed AppDbContext or AppDbContextMySql? In other words, is the model only used to generate migration scripts, or is it also needed at runtime to help EF handle the data in any way?
The short answer is yes, the model is definitely needed in all the cases.
Generating migrations from it is just one of the possible usages, and for sure not the primary - migrations are optional feature which may not be used at all.
The primary purpose of the model is to provide the mappings between the data (objects, properties, navigations) and the storage (database tables, columns and relationships). It is basically the M part of the ORM (Object Relational Mapper) what EF Core is.
It controls all EF Core runtime behaviors - LINQ queries, change tracking, CUD etc. Like what is the associated table/column name, what is the PK/FK property/column, what is the cascade delete behavior, what is the cardinality of the relationship and many others.
The way you asked the question makes me think you are assuming that the model is used just for migrations while at runtime EF Core takes that metadata information from the actual database. That's not the case. For EF Core the database is whatever you told them in the model configuration. Whether the physical database is in sync (correctly mapped) is not checked at all. That's why people start getting errors for non exiting columns in their queries when they screw-up some fluent configuration, or more importantly - do not include such.
Which is the main drawback of using separate (a.k.a. "bounded") contexts for a single database. Because having a DbSet type property in the derived context is not the only way the entity is included in the model. In fact typed DbSet properties are just for convenience and are nothing more than shortcut to the DbContext.Set<T>() method. A common (a sort of hidden) method of including entity in the model is when it is referred (either directly or via collection) by another already included entity. And all that recursively.
And when the entity is included in the model, it needs the associated fluent configuration regardless of the concrete context class. Same for referenced entities, and their references etc.
So I don't really see the benefits of "bounded" context classes - they probably work for simple self containing object set with no relations to other (and vice versa), but can easily be broken by this automatic entity inclusion mechanism.
For reference, see Including types in the model and Creating and configuring a model.
So I have code which has created a poco entity (from deserializing JSON). I wish to enable lazy loading for the the entity, so I want Entity Framework to wrap my POCO object and give me an EF proxy that can lazy load navigation properties.
I've seen many answers for questions regarding getting the underlying poco entity from an EF proxy, but not the other way around given. Given a poco entity how do you create an EF proxy wrapping it?
Both...
context.Set<TEntity>().Add(poco);
and...
context.Set<TEntity>().Attach(poco);
...return the poco entity is there a method somewhere that will give me a proxy for the poco?
I'm able to get proxied entities and lazy loading is working fine when I load an entity through...
context.Set<TEntity>().Where(...)
You can't lazy load navigation properties unless you are querying from the context. If you are loading the entity by the deserialization of JSON you need to use explicit loading.
//Example
context.Entry(poco).Reference(x => x.ReferenceProperty).Load();
context.Entry(poco).Collection(x => x.ReferenceCollection).Load();
https://msdn.microsoft.com/en-us/data/jj574232.aspx
I'm relatively new to NHibernate. I'm working on a web app in which i need to detach the entity from Hibernate session and pass it to UI for changes. I'm using NHibernateUtil.Initialize for eager loading of the entity. The problem i'm facing is the entity has a lot of collections and some collections have even child collections, so when i'm using NHibernateUtil.Initialize it is eager loading all the collections, which in turn increasing my JSON data that i pass to UI layer.I'm using ASP.NET Webapi in the service layer. Is there a way to control the eager loading to only particular collections that i need in the entity . Any help would be appreciated
Thanks
In your mapping you can specify the default behaviour for lazy loading of collections and references. How are you creating you mappings? You can override the default by specifying a fetch strategy in individual queries. What module are you using for your query (QueryOver, Linq etc.)? My preference is to always set the default to lazy load and then eager fetch as required.
Also, my preference is to not pass the entity directly to the UI layer but to create a ViewModel in the Controller.
My model turns my join tables into a many-to-many relationship in the model editor. This means that when I query a table through the many-to-many relationship to a row in the other table, I get the EntityCollection instead of IQueryable.
It is my understanding that it is more efficient to stick with IQueryable because EntityCollection loads instances of the entity classes into memory then queries those.
I'm not sure it's exactly what you're looking for, but EntityCollection<T>.CreateSourceQuery() will return a new instance of ObjectQuery, which implements IQueryable<T>.
Check out http://www.asp.net/entity-framework/tutorials/creating-a-more-complex-data-model-for-an-asp-net-mvc-application and look in the Customizing the Database Context section. There is a fluent API example of how to use join tables on many-to-many relationships. When I have a DB already defined, I like to create my own model classes and use Fluent API and Data Annotations to link them to the appropriate tables. That way I control how the application uses those tables instead of trusting the framework to build the way it thinks it needs to be built. This does two things: 1) It ensures that you are familiar with how the app uses your data, and 2) gives you more control over how data is represented in the app.
Happy coding!
Is there a way to get entity objects to automatically pull all relevant data through the relationships instead of having having to .Include everything I want populated? I can't use lazy loading as this needs to be serialized to go over WCF. It would just be fantastic to have it auto populate the relevant collections.
No there is no build in feature which will automatically eagear load whole object graph. You must always explicitly say which navigation properties you want to eager load (by using Include method or LoadProperty method).
Edit:
Based on your comment: Generally it should be possible to build some auto loader - but it will not be easy. ObjectContext has MetadataWorkspace property which contains all metadata about your entities. You can load all information about your entities from metadata and add needed inclueds to the query. I expect one problem - you must somehow handle cyclic references. If you need some example how to extract information about entities check T4 POCO generation template.
I came across this querstion recently because I was looking for something similar.
Since EF Core 6 there is a AutoInclude method that configures whether a navigation should be included automatically.
This can be done in the OnModelCreation method in the DbContext class:
modelBuilder.Entity<Theme>().Navigation(e => e.ColorScheme).AutoInclude();
This would load the ColorScheme for every Theme when running the query:
var themes = context.Themes.ToList();
See Model configuration for auto-including navigations