Does DDD and Automapper defeat lazy loading? - c#

I'm working on an n-Tier Domain Driven Design project that uses Entity Framework 4 DB-First and Automapper to produce POCO's in the Domain's namespace.
To clarify: The EF project returns entities in the MyProject.Repositories.EF.Entities namespace and I use Automapper to turn them into entities in the MyProject.Domain.Entities namespace.
Now, I can't quite make out if when I map between the EF and Domain entities, if all the collection properties are enumerated, i.e. if all the related data is also retrieved from the DB when they are mapped, or if they are still only lazy loaded when I actually enumerate them in code.
I am concerned about the obvious performance implications.

Turns out the answer is no. As long as you map between two IEnumerables, the actual enumeration will only take place when you perform a foreach, ToList(), etc. If you don't perform actions on IEnumerable properties of these objects, the enumeration will never happen and the related data will not be retrieved.

Long story short - this is not a concern of AutoMapper, but of how you use your ORM. AutoMapper merely removes code you would have already written, so if you would have written lousy performing code against your ORM, AutoMapper will happily oblige.
People were abusing ORMs before AutoMapper, while using AutoMapper, and after using AutoMapper. Lazy loading is a powerful tool when used correctly, but still can be abused. Using lazy loading does not preclude the developer from understanding what is actually happening underneath the covers.
So use AutoMapper, but take care with your fetching, just as you should be doing had you NOT used AutoMapper.

Related

What would be the consequences if I disable the ProxyCreation globally in Entity Framework?

The Entity Framework uses proxy classes for some of its internal stuff, as seen in this question we have to disable it, because it cause issues with the serialization of the objects.
My question is what will be the consequences if I disable the ProxyCreation globally in my project (to avoid serialization issues) ...???
They are mainly around enabling lazy loading, but can provide some performance improvement for persisting changes, though honestly I'd say this is highly situational to present anything that is noticeable.
I would be cautious about the need to serialize entities. For instance if it is to return entities from a controller/API I would recommend defining POCO view models or DTOs that reflect the data needed by the consumer for this purpose rather than serializing the entities. The key reasons for this is that serializing entities can expose more information about your data than the consumer needs, which also means more data sent across the wire than was needed. It also can represent a misleading representation of the data in the sense that collections/references that are not eager loaded will be #null, so does that later mean that they have no data, or that it simply wasn't loaded?
Autofac supports .ProjectTo<T> which integrates into EF's IQueryable operations to simplify mapping to view models vs. using .Select.

Mapping DTO to Entity

I'm trying to map DTO's to Entities. When I searched it online I noticed lots of references to AutoMapper and just as much feedback about how it is not a good way to do this.
Also I couldn't find any newly dated sources, one question complaining about how there are no "new" sources is 4 years old.
One of the sources I found, which looked really promising was this
https://rogerjohansson.blog/2013/12/01/why-mapping-dtos-to-entities-using-automapper-and-entityframework-is-horrible/
and I couldnt get it working either.
So, basically situation is like this.
I'm trying to do an integration about orders by using wcf. (A whole another case)
I have an order dto and related dto's are orderline, customer, customeraddress, orderadress. Some more will follow later.
Since these are essentially database tables, main "table" is Order. It acts as the header, orderline and others are self explanatory. I'm sure everyone came across something like this before.
I created Dto's according to their counterpart entities.
What I'm told to do is;
a) Convert (or as terminology goes, map?) these DTO's to Entities
b) Add the entity to dbcontext and savechanges.
So, can anyone point me in a good direction on solving this situation?
We have a similar project as you. Instead of WCF we use Model classes from MVC, but finally is the same idea: to convert from one object to another. I cannot disagree more about AutoMapper. At first, we had the same doubts about its efficiency, but finally we decided to give it a try. Then, we faced some of the problems the article pointed (especially the collections of elements). Luckily, AutoMapper gives you enough flexibility to handle those special mapping conditions.
For collections we use custom mappings, which allow us to detect when we have new elements / elements to update / elements to remove
For references, we follow the rules of Entity Framework: add the FK_Id value rather than the real object.
If, for some reason, you need to add some logic on the mapping, based on some reference entities, then we use dependencyResolver (only on extreme cases, as we don't like the idea of dependencyResolver)
I think AutoMapper is easy enough to learn the basics, so you can map your objects if a matter of minutes. Plus, it gives you all the tools for the special considerations.
The article you posted explains how "Entity Framework does not like AutoMapper", but its more related on how you follow the rules of EF and AutoMapper. Entity Framework is a huge ORM and, as such, you need to follow some rules (very strict rules in some cases). Of course, using AutoMapper with the basic examples will break some rules, but once you start to get used to it, is really easy to follow the rules.
To sum up: AutoMapper saves you a lot of time, that you can invest on customize some configurations. If not, you will have to use linq projections, which in most cases will take you much more time. For example: the collection problem is solved by detecting the add/edit/delete based on Ids, which can also be handled with AutoMapper through custom mappers.

OData vs EF Code First Fluent API or both? [duplicate]

While we mostly use fluent configuration for our code-first POCOs, we have found it useful to use data annotations for things like the table name, PKs, etc. since it makes it easier for non-EF components that don't have a reference to the ObjectContext to interact with these entities.
In our experience, it seems that the two configuration styles can be mixed freely, with fluent configuration overriding DataAnnotations. Is this documented anywhere? Is there any risk to doing this mixed configuration?
We are currently using EF 4.3.1
You can use Data Annotation attributes and Fluent API at the same time. Entity Framework gives precedence to Fluent API over Data Annotations attributes.
I personally haven't ran into any issues with mixing the code first fluent api and data annotations. I also wondered if there would be any crossover pain and I can honestly say I have yet to find any. Here's a few references to case studies on the subject to ease your mind.
(Direct from the EF team)
http://msdn.microsoft.com/en-us/data/jj591583.aspx
(Part 1)
http://www.codeproject.com/Articles/476966/FluentplusAPIplusvsplusDataplusAnnotations-plusWor
I don't think it's a risk - as both things have equivalent counterparts for the most of it.
But, personally, when I run into some sort of issues around structuring my entities - first thing I do is to remove annotations if any - and move all to fluent.
Which over time led me to use pretty much straight fluent configuration (also freeing my my objects of any ties with the Db 'state of mind')...
IMO it is 'safer' but only in a way that you can do more and control
things exactly as you'd want them. Also helps with keeping things
consistent and in one place.

Data Access Framework that addresses my needs

I'm having trouble choosing an appropriate data access framework, partly because I'm very picky with my preferences and mostly because I don't have much experience with most of them :-)
I need a framework that will allow me to easily map between the DB tables (SQL Server) and my entities, and that will handle the CRUD operations for me (for the most part).
I want my entities to reside in a separate assembly from my DAL.
I prefer using attributes for the mappings over external file like XML.
It doesn't have to be an ORM, and I want to code my entities myself.
I don't mind writing stored procedures.
The project's database won't be very big. Less than 50 tables.
I'd like some of my entities to correspond to an inner join of two tables - one for static data entered manually during development and the other with data filled during runtime - without using two entities that reference one another (the result of this join will be a single entity).
Entity Framework sounded perfect until I realized it doesn't support Enums (yet - and I can't wait for EF 5.0).
I want these entities to include Enums, and plan on using lookup tables for the enums + code generation for the enum to keep it synchronized with the database.
Linq-to-SQL seems like a good candidate, but I don't know if it copes well with my previous demands.
Using Enterprise Library 5.0 DAAB with it's RowMapper, and extending it's abilities to perform updates and inserts is also an option (but will require more coding on my part).
I plan on implementing the Repository Pattern.
How about NHibernate? Would it do? No experience there either.
I would be happy to hear all suggestions.. the more the merrier! Thanks in advance!
I think nHibernate is the way to go, although some of its main strengths (ORM, stored procedure generation, etc) are things you listed as non-requirements. Anyway, nHibernate will do everything you want it to do. Technically it does use xml mappings, but these can easily be auto-generated using fluent attribute mapping. I like this, as it IS done for you, but you get the customization too just in case you need it. Good luck!

It is possible to use WCF + DTO's + Automapper?

I want to use automapper with a structure that uses WCF + DTO's but I want to know how the question of the eager loading with entity framework 4.0 work with the mappings of the automap.
I recently use Automapper with LightSpeed ORM (which makes Entity Framework look like a prototypea btw). It just works. It wont matter if your entities are eager or lazy loaded or used via WCF or not. Automapper is resolving the referenced entities the same way you would in your own code.
"well, I just want to know if there is any issues with eager loading and the automapper auto-mapping feature. "
No.
In fact so "No." that it makes me wonder why you would think there would be problems.
Eager loading fills properties up with data.
Automapper moves property values around.
What exactly are you trying to do?

Categories