Automappers vs Manual mapping during web development - c#

I am working on a web application which implements DDD principles and using Asp.net web api and Entity Framework.
I know that my question is weird, but anyway I am looking for guidance from people who experienced that.
In the past I was doing mapping between dtos, domain models and data models, but recently I found it hard every time to do that.
Is it a reliable way to depend on built-in automappers to handle mapping for our applications, and what are the available built-in automappers to use them with web application as c# and Entity Framework?

I would say that using Automapper is quite useful, saves a lot of time and makes me focus more on the domain logic rather than mapping issues.
I have used http://automapper.org/ in many projects I have done and it is very powerful specially when understand how to configure the mappings the right way.
For sure there is a performance cost on using Automappers rather than manual mapping (in most of cases) but when considering the development time it saves, it worth a try.
There are many articles and questions talking in more details about this subject and comparisons with different mapping methods and tools:
http://geekswithblogs.net/mrsteve/archive/2016/11/29/object-mapper-performance-comparison-revisited.aspx
Which is faster: Automapper, Valuinjector, or manual mapping? To what degree is each one faster?
https://softwareengineering.stackexchange.com/questions/167250/am-i-wrong-in-thinking-that-needing-something-like-automapper-is-an-indication-o
and much more, just google it...

Related

NHibernate (or other worth recommendation ORM), real life example?

I'd like to learn database applications in C# and I'm about to select some framework. I heard many recommendations of NHibernate, however I haven't decided yet.
Anyway, I'd like to know if there's any real-life example (with sources) of NHibernate in C#, to learn best practices etc.? I know all of them are probably covered in the docs, but working example helps a lot understanding the proper development pattern.
Check out Ayende#Rahien, there's a lot of blog entries on NHibernate there. Another good source is NHibernate Forge. To get you started this would be especially helpful: NHibernate Getting Started Guide. Finally here you can find a downloadable working example of a NHibernate project based on the Northwind database.
The open source project S#arp Architecture is so far the best example I'm aware of for NHibernate:
S#arp Architecture
Even if it feels sometimes a little bit overdesigned, it follows best practices in implementing NHibernate in a multi-tier architecture.
I personally learned a lot about ORMs and good loosely coupled architecture going through
the code of the project.
Another worthwhile article about NHibernate can be found on CodeProject:
NHibernate Best Practices
Real life example: Orchard uses NHibernate, Fluent NHibernate and Linq To NHibernate for data access. It is an opensource CMS build by Microsofties. Source code is available at CodePlex.
NHibernate is a very solid ORM which allows you to create POCO classes, keeping your domain model very clean and allowing easier testability.
Entity Framework is improving rapidly. The UI tools in EF4 are okay for small applications but it is difficult to manage that kind of development with version control, rapidly changing DB schema etc. With EF4 Code First approach (in CTP stage at the moment) EF4 will will be much more attractive.
I have used LLBLGen in past with great success.
For beginners, Webmatrix can get you started very quickly. Check Rob Connery's video on how to use it with testing framework here
As others have said, NHibernate is a solid framework to work with. It's quite mature and has a lot of features that let you control exactly what will happen to your date.
That said if you're just starting out with database programming you may also want to consider LinqToSql. It's not nearly as powerful as NHibernate, and it has been more or less EOLed. However, what you give up in power you gain in simplicity. It will allow you to get a basic database application up and running probably within minutes and allow you to experiment as you first learn. Despite the simplicity of getting your first app up and running it's still powerful enough to be used to build something like Stack Overflow.
Some good Linq to Sql beginner resources:
NerdDinner
ScottGu's series: Using LINQ to SQL (link is to part 9 because that has links to 1 through 8 at the top). Although this one doesn't have an application download (best I can tell) it basically walks you through building an app.
If you have your heart set on learning NHibernate, you can also start with the NerdDinner tutorial linked above and take a look at Ayende's writeup on porting it to NHibernate as well as a series on mapping NerdDinner with NHibernate. There's also a series of articles on using NHibernate in a WPF application (most other tutorials focus on web apps).
Resources:
Ayende's Reviewing NerdDinner and Reviewing NerdDinner: The Select N+1 pitfall
NerdDinner with Fluent NHibernate Part 1 - The domain model
NHibernate and WPF (again, links to part 4 that has link to parts 1 - 3).
One thing I can't emphasize enough is once you get past the initial "cool...I can talk to the DB" phase, grab a trial license for an appropriate profiler (list of profilers at the top) for your platform. It will let you see what exactly your ORM is sending to the DB. It can be very valuable for learning how what you're doing gets translated into SQL as well as troubleshooting bugs you run into.
Regardless of which path you choose you should also take a look at Data Access Practices Using Microsoft .Net: A Nerdly Comparison and Data Development GPS: Guidance for Choosing the Right Data Access Technology for Your Application Today. Although those only cover Microsoft technologies, it'll give you a high level overview of what's available out there and when it may and may not be appropriate for your projects (in the future).
Take a look at NHibernate addins project http://code.google.com/p/unhaddins/
Though this is not real life production example, the sample applications there are pretty close to real life applications | scenarios. The examples there are written by well known and respected programmers and they show some serious OOP and design patterns skills. This is definitely not for beginners.

Linq to SQL ORM 3-layer question

I am designing this HR System (desktop-based) for a mid-size organization. The thing is I have all the tables designed and was planning on using the O/RM in VS2008 to generate the entity classes (this is the first time I work with OR/M; in fact, this is my first "big" project.) I wanted to make the app with 3 layers (one of the programmers of the company suggested not 3 but 4 or 5 layers) but after reading quite a lot of blog entries and a lot of questions here I've realized that is not quite easy to do that with LINQ to SQL because of how the datacontext works and how difficult it is to pass objects between layers using LINQ to SQL.
Probably I'll just use the entity classes generated by the VS2008 ORM and add any validation and bussines logic in partial classes. But that would be 2 layers, or not? The app will be used by like 10 users, so I don't think the 2 layer approach is a big issue for now.
In the future, a web-based front-end will be developed so candidates can apply to jobs online. I want to develop it as scalable as possible. But the truth is I don't have a lot of time to waste to make a decision, times running up hehe.
Having said all that, should I just use the entities generated by the VS2008 ORM?
So any suggestion or idea would be greatly appreciated. Thanks.
You're chewing over quite a lot with your line of questioning here. (Is there a concrete question hidden in there somewhere?)
With layers, I assume you mean physical boundaries, i.e. application, app/SOA/WCF server, data layer that lives on the SOA server, and a database somewhere.
Designing for the future might seem like a good idea, but DO make sure that there WILL be a need for all those layers somewhere down the line. Essentially, you do not need a WCF/SOA based approach if you're not exposing your application over the internet at some point. A web frontend can solve the same problem in many cases.
I'm not saying you will not need those layers at all, but you might not. If you really do, seams are your friend. You need to make "cut points" where you can define your boundaries. I commonly use the repository pattern to diversify data access methodologies, and use plain objects (POCO) and interfaces that are persisted via technologies such as NHibernate. Using POCOs also makes it MUCH easier to transfer those objects over the wire at a later point, either standalone or part of messages.
Creating service interfaces that are called can solidify your boundaries. When you are ready to move cross-machine/physical boundaries, you simply create your boundaries in the service implementations.
It sure sounds like a dangerous way to go - creating the tables first, then domain and finally GUI.
I must admit I am no expert on ORM expert but the generated classes I´ve seen looks more like dataobjects than classes. I would say you need another layer to stop all logic to end up in the GUI ).

When NOT to use the Entity Framework

I have been playing around with the EF to see what it can handle. Also many articles and posts explain the various scenarios in which the EF can be used, however if miss the "con" side somehow. Now my question is, in what kind of scenarios should I stay away from the Entity Framework ?
If you have some experience in this field, tell me what scenarios don't play well with the EF. Tell me about some downsides you experienced where you whished you would have chosen a different technology.
The Vote of No Confidence lists several missteps and/or missing bits of functionality in the eyes of those who believe they know what features, and their implementations, are proper for ORM/Datamapper frameworks.
If none of those issues are a big deal to you, then I don't see why you shouldn't use it. I have yet to hear that it is a buggy mess that blows up left and right. All cautions against it are philosophical. I happen to agree with the vote of no confidence, but that doesn't mean you should. If you happen to like the way EF works, then go for it. At the same time I'd advise you to at least read the vote of no confidence and try to get a rudimentary understanding of each of the issues in order to make an informed decision.
Outside of that issue and to the heart of your question - You need to keep an eye on the Sql that is being generated so you can make tweaks before a performance problem gets into production. Even if you are using procs on the backend, I'd still look for scenarios where you may be hitting the database too many times and then rework your mappings or fetching scenarios accordingly.
One potentially big issue: Entity Framework 1.0 does not support persistence ignorance. This means that your business layer has a dependency on your data access layer.
If your entire application will be hosted in the same process (like a website on IIS) then this is no problem.
If, however, you have a need to remote your entities (to a Silverlight or Windows Mobile client for example), then your entities will not easily serialize across the wire. You will have to create separate data transfer classes to send your entities across the wire, and additional logic to marshal data between your entity classes and the DTOs.
Edit: spelling.
I'm also just at the 'playing around' stage, and although I was worried about the lack of built-in persistence agnosticism, I was sure there would be a "work-around".
In fact, not even a work-around in an n-tier architecture.
WCF + EF
If I've read the article correctly, then I don't see any problem serializing entities across the wire (using WCF) and also the persistence ignorance isn't a problem.
This is because I'd use PI mainly for unit-testing.
Unit Testing is possible! (i think)
In this system, we could simply use a mock service (by wrapping up the call to the service in ANOTHER interface based class which could be produced from a factory, for example). This would test OUR presenter code (there's no need to unit-test the EF/DAL - that's Microsoft's job!) Of course, integration tests would still be required to achieve full confidence.
If you wanted to write to a separate database, this would be done in the DAL layer, easily achieved via the config file.
My Tuppence Worth
My opinion - make up your own mind about the EF and don't be put off by all the doom and gloom regarding it that's doing the rounds. I'd guess that it's going to be around for a while and MS will iron out the faults in the next year or so. PI is definitely coming in according to Dan Simmons.
EDIT: I've just realised I jumped the gun and like a good politician didn't actually answer the question that was asked. Oops. But I'll leave this in in case anyone else finds it useful.
Not all data models map nicely to application Entities. If the mapping isn't relatively straightforward, I'd skip the Entity Framework. You'll find yourself doing handstands to make it work without any clear benefit.
Anders Hejlsberg had some interesting comments about object/relational mapping here.
Since EF does not support POCO, it can be difficult to write good unit tests against. That was one of the knocks against it in the Vote Of No Confidence.
If you're wanting to write good tests, EF will raise obstacles. You can work around them, but it is non-trivial.
Though both SQL CE 3.5 SP1 and Entity Framework 4.0 Beta 1 both support Identity Columns, using these two products together (at least up to the versions listed), Identity Columns are not supported. You will be required to set primary keys on your own.
Other than that, I've been enjoying EF with SQL CE.

What ORM to Run: telerik Open Access VS Subsonic VS linq to sql VS Active Record

We are looking into using an ORM and I wanted some opinions/comparisons
The basic criteria we have for an ORM is: Easy to use/configure(short learning curve), flexible, the ability to abstract it away, easy to maintain
Here is a list of what ORM we are looking at and what our initial impressions are
Open Access - seems really easy for simple stuff, but doesn't seem to have a lot of flexibility, cost isn't an issue we already own it
Ling to SQL - looks very simple to use and configure but is missing some functionality
Active Record - NHibernate made simple
SubSonic - looks very feature rich, but haven't really played with it much
here are the ORMs we have looked at and ruled out
Entity is still in beta
NHibernate has far to much of a learning curve (we don't have 3 weeks to delicate to learning it)
I'd say you should take a look at DataObjects.NET (http://www.x-tensive.com). It's feature rich and pretty easy to use. It does, though, absolutely tie you to your object model, as it decides what the database structure should be based on what your object model looks like. That being said, if you want to be able to disregard the existence of the database, it's quite nice. We've used it for years and have had great success.
We currently use SubSonic (2.0.3) and it has been an absolute lifesaver. I cannot stress enough how awesome it is. HOWEVER, we are now looking at switching away from it for various reasons (probably to NHibernate or Entity). Here are my Pros and Cons of it:
Pros:
Very simple to setup and use.
Lots of great & useful, tools and features
Uses the "convention over configuration" philosophy, so very little configuration. It "just works". (As long as you do things the way it wants... :) )
Cons:
Your database design is very tightly coupled to your domain design. Make a change in your DB, and you need to change your code/domain design.
By default, SubSonic uses the ActiveRecord pattern for all data access instead of the Repository pattern, which makes it more difficult to "abstract it away". (Although I believe with v3.0 that you can swap out the default ActiveRecord templates to use the Repository pattern).
Lots of pessimistic rumours flying around about the future of SubSonic. But rumours are just that: Rumours.
For all the paired pennies it may be worth:
If you don't have 3 weeks now to learn your ORM of choice (whichever you choose), you may have to find 3 weeks to learn it later when it doesn't map something exactly how you thought it would.
If you have a model that's moderately complicated, ORM is non-trivial. You'll wind up needing to know how your ORM works so you can tell it to map things the way you want.
Which is all another way of saying "Know thy tools", of course. :)
Most folks will have a smattering of experience with one or two of those, but few will have exposure to all. I recommend a proof-of-concept effort with each of your favorites. Get each one set up, spending no more than n hours per ORM tool (n = however much time you decide is reasonable.) You don't have to implement your entire object model, a functional subset will do.
By the time you're done, you will have worked through the setup and some usage of all of them. You can then write up a post-mortem and the team can decide which has the best pain-to-feature ratio.
Use T4 templates to create your own. There are several established patterns available on the internet especially for T4 templates.
Knowledge of T4 also will allow you to script out items that might have a large scope than macros, but a smaller scope than writing a custom app to generate the script you need.
Hope this helps!
I very much agree with BryCoBat (upvoted). I wanted to also add that if you already own Open Access, then the company very likely has people somewhere internally who are already very comfortable with it, including code examples you look at in your own domain for both trivial and non-trivial tasks. In other words: use what you know.
If you're not using Telerik controls, LINQ to SQL should be the one to select for fast learning - there is huge amount of different tutorials, videos, books in the web.

Whats the pros and cons of using Castle Active Record vs Straight NHibernate?

Assuming that writing nhibernate mapping files is not a big issue....or polluting your domain objects with attributes is not a big issue either....
what are the pros and cons?
is there any fundamental technical issues? What tends to influence peoples choice?
not quite sure what all the tradeoffs are.
The biggest pro of AR is that it gives you a ready-made repository and takes care of session management for you. Either of ActiveRecordBase<T> and ActiveRecordMediator<T> are a gift that you would have ended up assembling yourself under NHibernate. Avoiding the XML mapping is another plus. The AR mapping attributes are simple to use, yet flexible enough to map even fairly 'legacy' databases.
The biggest con of AR is that it actively encourages you to think incorrectly about NHibernate. That is, because the default session management is session-per-call, you get used to the idea that persisted objects are disconnected and have to be Save()d when changes happen. This is not how NHibernate is supposed to work - normally you'd have session-per-unit-of-work or request or thread, and objects would remain connected for the lifecycle of the session, so changes get persisted automatically. If you start off using AR and then figure out you need to switch to session-per-request to make lazy loading work - which is not well explained in the docs - you'll get a nasty surprise when an object you weren't expecting to get saved does when the session flushes.
Bear in mind that the Castle team wrote AR as a complementary product for Castle Monorail, which is a Rails-like framework for .NET. It was designed with this sort of use in mind. It doesn't adapt well to a more layered, decoupled design.
Use it for what it is, but don't think about it as a shortcut to NHibernate. If you want to use NH but avoid mapping files, use NHibernate Attributes or better, Fluent NHibernate.
I found ActiveRecord to be a good piece of kit, and very suitable for the small/medium projects I've used it for. Like Rails, it makes many important decisions for you, which has the effect of keeping you focused you on the meat of the problem.
In my opinion pro's and cons are:
Pros
Lets you focus on problem in hand, because many decisions are made for you.
Includes mature, very usable infrastructure classes (Repository, Validations etc)
Writing AR attributes are faster than writing XML or NHibernate.Mapping.Attributes IMHO.
Good documentation and community support
It's fairly easy to use other NHibernate features with it.
A safe start. You have a get-out clause. You can slowly back into a bespoke NHibernate solution if you hit walls with AR.
Great for domain-first development (generating the db).
You might also want to look up the benefits and drawbacks of the ActiveRecord pattern
Cons
You can't pretend NHibernate isn't there - you still need to learn it.
Might not be so productive if you already have a legacy database to work with.
Not transparent persistence.
In-built mappings are comprehensive, but for some projects you might need to revert to NHibernate mappings in places. I haven't had this problem, but just a thought.
In general, I really like ActiveRecord and it's always been a time saver, mainly because I seem to happily accept the decisions and tools baked into the library, and subsequently spend more time focusing on the problem in hand.
I'd give it a try on a few projects and see what you think.
When I started using NHibernate, I didn't learn about Castle ActiveRecord until I had written my Mapping files and made my classes. At that point, I couldn't visibly discern what Castle Activerecord would give me, so I didn't use it.
The second time I used NHibernate, I simply used myGeneration to make the mapping files and the classes just by having it look at my database. That saved a lot of time by itself, and allowed me to (once again) not worry about Castle Active Record.
In reality, most of your time is going to be spent making the custom queries, and Castle Active Record won't necessarily help with that -- if you were to use myGeneration with NHibernate, you'd bypass most of the work you'd need to do anyway.
Edit: I don't want to seem like a cheerleader for either myGeneration or NHibernate. I just use the tool that allows me to get my work done quickly and easily. The less time I have to spend writing Data Access code, the better. It doesn't mean I can't do it -- but there's little sense in re-inventing the wheel each time you write a new application. Write SQL queries and Stored Procedures where needed, and no where else. If you're doing CRUD operations, an ORM is the way to go.
Edit #2: Castle Active Record may bring more to the table than I realize -- I don't know much other than what's on their website, but if it does bring more to the table, then it would help potential adopters to be able to readily see that on their site.

Categories

Resources