MVC total noobe here but long time web developer - 10 + years. The tutorials for MVC 3 (and earlier versions) are great but as usual they lack a ton for real on the job type scenarios.
For example, how often do you find yourself in a situation where you are going to create a new database from scratch with no stored procs so that you could actually use EF Code-First. I don't know about you but in my career it has been NEVER.
The usual story is that you are creating a new app or enhancing an existing app with new functionality that will connect to an existing very mature database with tons of stored procs, user defined functions and views and you are required either by management or time restrictions to use it all. And of course you may get to create some new tables but they usually will have joins to existing tables or in the least your app will have to query existing tables for some of the data.
To see a tutorial based on that scenario would be WORTH IT'S WEIGHT IN GOLD. Especially the stored procedure scenario.
Thank you for any advice
Most of the earlier examples (e.g. the original NerdDinner) were based on either Linq to Sql or Entity Framework (without CodeFirst). Since CodeFirst is the 'new hotness' most of the latest examples use it.
The interesting part of the question, though, is that it highlights an important point: "it doesn't matter". Your data access strategy (EF, EF code first, NHibernate, L2S, raw SQL) is totally irrelevant to MVC. By that I don't mean it's unimportant, I mean that MVC doesn't place any constraints on you at all in that regard.
You will generally (in a well-designed MVC app) pass your controllers interfaces which let them call data access methods of various sorts (or perhaps another layer of indirection with services that do other things before hitting the storage layer). The implementation of the data access, if it is using an ORM like EF or Nhibernate, will then have mechanisms for you to either use a query syntax of some sort (e.g. LINQ) or to call stored procedures (possible in all major ORMs that Iv'e used) or to push raw SQL if hte situation calls for it.
Related
Warning : Noob Question !
I am being pushed into using MVC & EF for my projects; both of which are new to me.
The MVC part I'm not too stressed about, but EF bothers me, there are some key concepts that my head just isn't around yet.
My database is a repository of millions of records which users will need to perform very complex searches upon.
Seems that the majority of articles I read are hooking the DB up to the Application with EF, and filtering data client-side. That's just a 'No' for me, and I can't imagine that I am the only one.
Then I have seen some articles that talk of pushing the filters back to the DB using LINQ/IQueryables.
That sounds more reasonable, at least I would not be bringing back more data than I need.
But my more complex queries would be nightmare to build in LINQ (I imagine).
Still, what bothers me, is that I have SQL Server to do all that heavy lifting for me. Store Procedures that can utilize most powerful mechanisms for the most complex queries imaginable. Isn't that what SQL Server was born to do ?
I am still thinking to bulldoze ahead with my old Skool brain.
Build Models that reflect my data tables/stucture.
Populate my Models 'manually' via Stored Procedures
Can anyone point out where I might be viewing all this wrongly ?
I know that there is heaps of info on Google, but most just jump into how to technically do 'A'... with little discussion over 'why' we are doing 'A' or what the alternatives are.
Thanks for any comment !
Point 1 :
Yes,you can start it as you mentioned.That is Build Models that reflect my data tables/structure.That means you're going to create everything by hand manually. Which is very tricky task hence you're already having the db.So I would like to suggest to use EntityFramework Reverse POCO Generator for generating the required models from your db.
Point 2 :
Yes,You can use Stored procedures with the EF code first.But be careful not to use EF core at this moment. B'cos the SP support is at the beginning level right now.So you can start with EF 6.X and later with the maturity of the EF core where you can move easily to the EF core world.
Point 3 :
You don't need to worry about the size of the records which you have to show on the UI. B'cos there having so many sophisticated UI components which are build for showing massive data on the UI. You can choose either from free or paid once.
We are doing a new project, for all devices and browsers compatibility we have decided to use asp.net mvc 4, Html5, css 3, for communicating with Database Entity Framework we want to use.
Our senior members(Manager, DBA(they are also new to mvc 4, EF)) in the team asking us to write every thing will be in the stored procedures while communicating Database so that maintenance becomes easy.
Is it the correct match if we go like that(MVC4+ EF + stored procedures)? Will i not get maintenance and performance if i go with Code first reverse engineering(because database tables are ready i want to do like that), Please reply.
Below is the flow we want to do, please correct me
As Database is already ready, so first we will write the stored procedures for communication with DB.
New Mvc 4 project and will add .edmx file(EF) and select tables and Stored procedures
in mvc controller or web api we write the consuming stored procedures
There is nothing technically wrong with ASP.NET MVC + EF + Stored Procedures approach, from the first sight.
But my experience show, is that typically it's huge overkill. The common problem I see is the conflicting interests between developers and DBA's. In most worst scenarios all DB releated stuff are controlled by DBA, so if developer what to add/change some feature he needs to wait for implementation of it by DBA (or wait for approve, which could also take long).
So, I personally see that as more bureaucratic way of development.
My own perpective is to be more agile on development and tools like Code First matches that. Stored Procedures could still play major role, while code/performance optimization, but not something to start with.
I agree that using stored procedures in the database is a good approach. Centralizing data validation and calculations in the database ensures data integrity. Client-side validation is important for the user experience but you must also ensure that you test the data validity in the database.
Using Entity Framework, you can generate entities which relate directly to tables in your database, or else you can design entities which use procedures for insert/update/delete operations rather than simple table updates.
In MVC you will use the entities as models to manage your data interactions.
Good luck
This is my personal view. I am sure others might have different ones. Since you are asking this question I am hoping you are open for discussions, otherwise I wouldn’t have bothered as this topic is like a religious discussion as lots of people have very strong opinions and are not likely to change them.
Personally I don't think stored procedures are meant to write business logic. They should be used for writing data access logic. I would only use a stored procedure if I want to optimize an expensive query such as a dynamic search but nothing else. You will get slightly less performance if you have your logic in the domain model, but its not even noticeable in most situations.
One of the strong arguments for writing business logic in stored procedures is because you can easily change some logic by changing your stored procedure. But should we really go and change the business logic of a deployed application without doing proper testing. What will happen if you accidently do a mistake? Doing a deployment is not such a big deal now with continuous builds and I don’t think as a professional developer you should take that risk.
When you decide to write your logic in stored procedures, you give up all the object oriented concepts and you end up writing some procedural code that we wrote maybe 10 years ago. C# language has come a long way now and you will not be able to use those new language features in heart of your application which is business logic. You also loose the visual studio features to refactor code, advanced and easy debugging features etc.
I also don’t like the idea of having triggers as it’s not visible in source code. Imagine someone new in your team trying to add a new feature some time later and if he doesn’t know that a trigger exists, he might write some incorrect logic.
If your application contains some complex business logic, (I am sure most applications do) you should have a domain model that contains not only just properties of your entities, but also your logic. Otherwise you will be falling in to the anti-pattern called anemic data model.
You will not be able to test your business logic by writing unit testing if you have your logic in stored procedures.
You will also not be able to deploy your business logic to multiple servers if you have them in stored procedures if your site becomes really successful.
You will also not be using all powerful capabilities of Entity framework and LINQ if you have all your logic in your stored procedures. You actually don’t need an ORM Mapper if that is the approach you are going to take.
This is what I would recommend for your project.
Even though you already have the database, you can still use code first approach of Entity framework. You can download the EF code first reverse engineer power tool and have the code first code auto generated for you. This is going to be a one off thing and after than if you have any more changes, you can directly do to the database and update the code first code accordingly. Fluent API is bit confusing at first, but you can easily learn that from the generated code.
Do not access your data context from the controller. Have a repository layer that will contain all your data access logic. You can access the repository from your controller. (This allows you to unit test your code by mocking the repository). There are lots of video tutorials on how to use the repository pattern on asp.net site.
Your domain model is going to be the entities that got generated from the Entity framework. Try to have your business logic in those models. It takes a little while to get use to the domain model pattern. But one you get used to it you will start to appreciate its benefits.
Hope this helps.
So I have a layered ASP.NET MVC proof-of-concept application with good separation between presentation concerns, business logic, and infrastructure concerns. Right now it is operating off of a fake repository (i.e. LINQ queries against static IQueryable objects). I would like to create a functional SQL repository now.
That said, I don't want to simply tie it into a database that has a 1-1 mapping between tables and entities. That wouldn't meet the business need I am hoping to solve (partial integration with existing database - no hope for convention over configuration).
Do you have suggestions for which ORM / mapping tools I should consider and/or avoid?
Do you have suggestions for articles/books I could look at to help me approach this topic?
Would it be better to simply use parameterized queries in this scenario?
Entity Framework in version 4 would definitely allow you to:
have a mapping between the physical database schema and your conceptual schema, e.g. having an entity mapped to several tables, or several tables joined together forming a single business entity
grab data from views (instead of tables directly)
use stored procedures (where needed and appropriate) for INSERT, UPDATE, DELETE on every entity
NHibernate sounds like a good fit for what you are looking for. You will be able to make your repositories call queries in either HQL or using the API, either way you can get to your database and shape the data to fit the way your repository is being used. It will always be hard to make a square peg fit into a round hole though. SO has lots of nice support when you get into using NHibernate, good luck.
As you mentioned in the question, it is very debatable to choose an ORM. Different people will have different project needs. I am not exactly sure what will take priority for you. Here is what I have tried myself.
NHibernate seems to be the most commonly used ORM in DotNet projects. I feel it suffers from a typical open source problem. It offers so many features but the documentation really sucks. If you have lots of time at your disposal you can give it a shot.
Another options is to go for something like Entity Framework. Its very easy to set up and get up and running. With version 4.0 and the CTP there is provison for code first as well as fluent mapping and configuration. Since you have said you would want to keep the domain model separated EF 4 will help you because it has a notion of conceptual model which is an abstraction over the mapping layer.
You can refer to few links below for the blogs I had written based on my experience
http://nileshgule.blogspot.com/2010/08/entity-framework-hello-world.html
http://nileshgule.blogspot.com/2010/09/nhibernate-code-first-approach-with.html
http://nileshgule.blogspot.com/2010/09/entity-framework-first-query-using.html
http://nileshgule.blogspot.com/2010/09/entity-framework-learning-series.html
I'm about to start developing a web-based application that I can best describe as a specialized version of 37Signal's Highrise contact management app, targeted towards service businesses such as lawn care. I've decided to use ASP.NET MVC to take advantage of my BizSpark membership and to leverage the C#/ASP.NET/SQL Server that I already know.
I'm doing a bit of research to choose an ORM for the project; I'm not sure if I should go with something lightweight such as LINQ to SQL or go with the big guns of NHibernate. At this point I don't envision the application as being overly complex. I essentially have these models:
Account
User (provided by ASP.NET, but I might need to extend it)
Customer
Job
where the following business rules apply:
The account is the master record (since it represents a subscriber) and everything else (users, customers, jobs) hang off it
A customer can have more than one job
There are two types of Customers: A "lead" and a "customer" - the idea is that customers can request a followup from a form that we provide and be automatically added to the account's customer database, and then an employee can follow up and schedule a job, which "converts" the lead
A job can be either one-time or set on a recurring schedule (e.g. every two weeks, once a month)
I have a bad habit of trying to overarchitect things. LINQ to SQL seems like it would suit my needs immediately, but I'm concerned about scalability in the future and whether the upfront costs of using a more feature-rich ORM such as Entity Framework or NHibernate would make up for itself in query effectiveness and optimization. I'm considering using Windows Azure to host the application.
Any thoughts?
Your model seems simple enough to be supported by Linq2Sql, Entity Framework, and NHibernate.
The biggest choice you need to make is do you want to follow a Domain Driven Design approach to software modeling or do you want to work with your objects as database rows. If you want to get fancy when mapping rows to objects NHibernate is the best choice. If your happy with a 1:1 between your business objects and database rows Linq2Sql and Entity Framework just fine.
NHibernate and to an extent Entity Framework support POCO objects that don't inherit from a base class and can be unaware of their persistence requirements. Linq2Sql can, but its hacky and weird.
As far as scaling goes all three of those ORM tools will get you pretty far yet AFAIK NHibernate has more options when it comes to splitting database servers up and handling cross-database IDs and there is even some Sharding support in the works.
NHibernate also supports the most providers, you can go from MSSql to MySql in an hour, with Linq2Sql and EF ( although support is forthcoming you can't )
So TL;DR:
NHibernate if you want better POCO support, more scaling features, and "there is a mapping for that" row->object mapping features. FluentNHibernate is awesome. You have multiple provider support
Entity Framework if you want better designer GUI support and are willing to wait for EF4, vs2010 for a fully featured ORM.
Linq2Sql if simple db access is all you need.
I've used all three and I'm least happy with EF1, EF4 is better but not as good as NHibernate.
I'm using EF4 with VS 2010 for all future "simple CRUD" apps and NHibernate when I need to get fancy.
My experience has been that the "up-front costs" of Entity Framework are about the same as LINQ-to-SQL for simple data models (assuming you have an existing database schema to work with).
A series of tutorials on getting a simple Entity Framework model up and running is available.
I'm not one of those "LINQ-to-SQL is dead!" people, but it does look like Microsoft intends to invest more in Entity Framework down the road. This to me tips the scales slightly in its favor over L2S. The ADO.NET team blog is a good place to keep an eye on for this.
You may want to consider SubSonic. It appears to be aimed directly at your sweet spot.
After that, I would consider NHibernate. NHibernate has minimal downsides and it can effectively "scale down" to your project. With NHibernate, you aren't boxing yourself in to a limited feature set like you would be with the Microsoft ORMs and SubSonic.
Inspired by the engine that runs stackoverflow.com, I have been working on developing a full-blown CRM and business-in-a-box solution over the last few months. I had lot of reservations about using LINQ to SQL as the ORM (discussion on stackoverflow.com and elsewhere pointed out the fact that the Entity framework was the 'in thing'),however, I found LINQ to SQL to be a breeze to work with, even with its known limitations. With LINQ-to-SQL, I could build a fully-functional prototype CRM within weeks. Currently, the CRM is in late stages of beta with few customers and some of them have quite a high volume of usage (1000s of lead and few dozen users). I haven't seen any noticeable, show-stopping issues with the ORM/database so far.
I have written quite a few SQL stored procedures (and used them with LINQ to SQL) where very complex joins were required. Since I come from a SQL/Microsoft Enterprise Library background, I find it easier to write complex stored procedures in SQL and keeping the basic CRUD operations within the LINQ to SQL layer
indyfromoz
I am currently wrapping up an asp.net mvc application. We used the S#arp Architecture. It is a "framework" that enables developers to leverage NHibernate, Fluent, and a myriad of other best practices tools (DI, etc.) Here is a link to the site.
http://wiki.sharparchitecture.net/
Our team absolutely loves this product and recommends anyone to add it to their technical arsenal when deciding on architecture paths.
I'd recommend this:
S#arp Architecture. It uses NHibernate but is highly pre-configured so that you can get up and running in literally few minutes - not only with data but also with MVC and other useful things.
ActiveRecord implementation - namely, Castle ActiveRecord. Thsi is very easy to use, but still you need to understand NHibernate a bit.
Linq to SQL with Repository pattern. You'll benefit from simplicity of L2S while will be prepared to future changes. Just google for "linq to sql repository".
As my ex-boss said, "it doesn't really matter what you choose, it's important to choose something and start working" ;-)
When linq to entities was released, everybody say that linq to sql is dead.
But most books and sample projects by microsoft employees, use mvc+linq to sql.
There is some reason for that? The linq to sql seems better for POCO, would it?
Linq to SQL had its origins in a thought experiment. Linq needed a proof of concept, and Linq to SQL provided that.
Since then, many in the user community (including a few prominent Microsoft employees) have embraced Linq to SQL as the lightweight SQL Server ORM of choice, especially for small projects like NerdDinner.
The furor began with this post by the ADO.NET team. In it, they said that Linq to SQL will be maintained, and features added based on user community feedback, but that the Entity Framework would be the primary focus of future data access efforts.
Many in the user community interpreted this move as "Microsoft is killing Linq to SQL."
Microsoft didn't help matters when it disabled the provider model for Linq to SQL by sealing some critical classes, effectively making Linq to SQL usable only with SQL Server. The Entity Framework will be the ORM of choice for multiple data providers.
Unfortunately, the Entity Framework seems not quite ready for prime time.
So it depends on who you believe. Do you believe the speculations (and they are just speculations) of many bloggers who say that Linq to SQL is truly dead and buried, or do you believe people like Damien Guard of Microsoft, who says that Linq to SQL has a long life ahead of it?
Linq-to-SQL is a great technology and very easy to use, so it's extremely well geared towards demos, and it's a perfect choice for smaller, more straightforward projects, too, where you have more or less a straight 1:1 mapping from your tables in SQL Server to your objects in memory.
And those are the most restrictive limitations of Linq-to-SQL:
SQL Server only
straight 1:1 mapping from tables to objects in memory
If that's okay with you, go ahead and use Linq-to-SQL ! By all means - MS is still adding features and fixing it for .NET 4.0 - it's not dead by a long shot.
Entity Framework in its v1 version available right now has some warts, as other posters have rightfully mentioned (no POCO support, no "domain design first" approach and many others). But the EF v4 feature set looks very compelling, and will give Linq-to-SQL a run for its money!
The main advantages for EF vs. Linq-to-SQL in an enterprise environment are its database independence (you can hook it up to Oracle, Firebird, DB2, many others) which can be crucial, and it's ability to present you with an object model that looks quite different from the physical storage model in the database (by virtue of the mapping between the conceptual layer and the physical storage layer).
So it's really a matter of what is it you need: do you need a quick way to get started (demos, simpler apps) - then your choice clearly is Linq-to-SQL (at least for now), or do you need a flexible mapping approach against a non-SQL Server backend - then your choice will be Entity Framework.
Marc
The only reason the samples were written with LINQ-to-SQL is because setting it up is fast and simple.
Otherwise you can use any ORM to suit you, whether it be EF or NHibernate or whatever.
Personally, I'd start getting used to the Entity Framework now. Since it has more features, is provider-independent, and being developed (perhaps) more aggressively. The two most common complaints I hear are lack of POCO and lack of Lazy Loading. It would appear that both of these are addressed in .NET 4.0 http://blogs.msdn.com/adonet/archive/2009/05/28/poco-in-the-entity-framework-part-2-complex-types-deferred-loading-and-explicit-loading.aspx
Besides being potentially faster (to get started with) or simpler, I'm not sure of any particular advantage to use LINQ to SQL, in the long run. Is anyone aware of any?
The nerddinner sample chapter written by ScottGu uses Linq-To-SQL, he does not endorse LINQ-to-SQL but does not promote LINQ-To-Entities either. With ViewModel (Stephen Walther has a nice post on this) & the repository pattern, LINQ-To-SQL is perfect for developing ASP.NET MVC applications
In my opinion, Linq to Entity is not a good candidate at the moment. One of the things that I've come to dislike about Linq To Entity is the lack of lazy loading, which drove me up the wall every time i wrote my repositories. I think, that's what killed it for me. The other thing is the whole issue with attaching and detaching entities which are being used by multiple instances of the object context. That was another killer for me, which resulted in a lot of hacking trying to recreate entity relationships and etc. Frankly, I think a better thing to do would be to wait for the next release of this framework. I think good things are coming for it :)