I have a small application developed in ASP.NET 2.0 WebForms. For learning purpose, I am thinking to convert this application to MVC 3 + Entity Framework. Below is the simplest example to simulate my application. Nothing fancy.
Application Layout:
(image should read "input fields" and not "files")
Architecture:
Key points:
Methods in Service layer is using ADO.NET SqlCommand ExecuteReader method to execute stored procedures
Most of the manipulation etc. logic is done in stored procedures. Hardly any manipulation of data in Service layer
Now I want to convert this application to MVC.
Questions:
What benefit do I get (technically) if I convert this application into MVC + Entity Framework?
How do I go about it?
I have looked at some basic MVC3 tutorials but they all talk about EF code-first, which I don't think will fit in my case since I want to use the existing stored procedures. Is that correct?
Note: I want to use the existing stored procedures. Say I don't have control on DB structure changes.
Update 1:
There isn't a single inline query in my application. Even the smallest little query is a stored procedure. Tons of them.
Using SQL Server and almost nil chances of changing to any other DBS.
Update 2:
My webforms application is 99% complete and can go live anytime but due to some business hurdles it hasn't. In mean while I thought if I can convert (i.e. develop) this to MVC, I will learn plus if it works out can go live (my first MVC) instead of the webforms one.
Before answering the specific questions I'll point out that you should probably seperate the choices into 2:
Converting the presentation layer to use MVC instead of WebForms.
Converting the data layer to use EF instead of ADO.NET.
Now for your questions
Benefits of MVC include better control over HTML, better testability, etc. Benefits of EF include abstracting away DB-specific things (you could theoretically replace SQL Server with MySQL, assuming an appropriate MySQL provider), LINQ support, etc. Of course there are also costs to such a transition.
Divide and conquer. As stated earlier you don't have to do everything at once. Start with the presentation layer and convert it to MVC. Remember that you can have mixed WebForms and MVC applications so you don't have to transition all your pages at the same time. Then convert your data layer to EF. Or start in the reverse order, whatever makes sense for your project.
[Not an expert in this topic] if you rely heavily on SPs than consider traditional EF. If you have only a few SPs then you could consider code first + handling the SPs with DataSets (potentially wrapped in custom built classes) to make everything work, though that might get complicated. As before, you don't have to move to EF if the cost is too high.
What benefits do you get? It is completely wrong question. You should ask what problems do I have with current solution and how will these problems be solved by replacing data access with EF or replacing presentation layer with ASP.NET MVC?
As I understand you want to do this just for learning purpose - it has no business drive. In such case there are some points which will get you some ideas:
If you don't want to replace existing SP logic with the common EF way you will get almost none benefits and you will not learn EF. EF allows using stored procedures either for retrieving mapped entities or for loading custom classes. Mapped entities usually represent either views or tables from the database - it is not clear here if you even want to define any mapped entities. The only benefit you get when loading custom classes is automatic populating of properties from the result set. It means that you will need class for each SP result which will have properties named exactly the same as columns in result sets. SPs in EF doesn't support multiple result sets (by default) and also doesn't support automatic loading of relations.
When moving from ASP.NET Web Forms to ASP.NET MVC + Razor you can be almost sure that non of your front end code will be usable in the new solution. You will simply create new project and do you front end from scratch.
As described by #marcind these two changes are completely independent - you can do one without other.
Related
My question is pretty simple: is it a good practice to place the .edmx file in the model folder in a Web application of an MVC3 project?
my answer is pretty simple, do not mess up presentation layer (Whole MVC application) with data access logic and data modeling.
Have at minimum 4 projects in your Visual Studio Solution, from bottom to the top:
1 - ProjectName.Interfaces (Class library, entities's interfaces);
2 - ProjectName.DAL (Class library, the only one allowed to even know the EF is used, the POCO entities implement the interfaces of project 1 using another file where you redeclare same objects using partial classes...);
3 - ProjectName.BL (Class library, Business logic, references the two projects above 1 and 2);
4 - ProjectName.Web (ASP.NET MVC application, Presentation Layer, references two projects 1 and 3 but NOT 2);
this to simplify things of course, based on my experience this is a solid design, a bit overkilling for very small projects but pays off in the long term.
in my view, the M of MVC, Model, is NOT the data model, is not the EF, is not there to do ORM bound to the specific database engine.
this answer is subjective of course and is based on my personal experience ;-)
I agree with Davide here completely I just want to add that you should also consider using the POCO templates to generate poco objects and not return entity framework objects to another layer because it then puts a dependency on the entity framework.
At some inevitable point if you don't pluck this out into a separate project, your direct data access code ends up thrown into your web code. I see it all the time (and we've all been guilty of it at some time)
I don't think this matters much.
I use CodeFirst, so my DbContext class goes to the Model folder.
Really, the EDMX is there just for the code generation, beyond that it does not do much, its not deployed/published to your server, etc. So where it stays isn't important. You could create another folder for it EDMX if you want, or put it in Model as you asked.
I've just finished going through the MvcMusicStore tutorial found here. It's an excellent tutorial with working source code. One of my favorite MVC v2 tutorials so far.
That tutorial is my first introduction to using ADO.NET Entity Framework and I must admit that most of it was really quick and straight-forward. However, I am worried about maintainability. How customizable is this framework when the customer requests additional features to their site that require new fields, tables and relationships?
I am very concerned about not being able to efficiently execute customer's change orders because the Entity models are basically drag-and-drop, computer generated code. My experience with code generators is not good. What if something goes haywire in the guts of the model and I'm unable to put humpty-dumpty back together?
In the long run, I wonder if using hand typed models which human-beings can read and edit is a more efficient course than using Entity Framework.
Has anyone worked enough with entity framework to say that they are comfortable using it in a very fluid development environment?
I have been using entity framework(V1.0) for about a year in my current project. We have 100s of tables,all added to the edmx.
Problems we face (though not sure if the new entity framework resolves these issues)
When you are used to VS.net IDE, you
will be used to doing all drag/drop
operations from your IDE. The
problem is, once your edmx hosts
100s of tables,the IDE really stalls
and you would have to wait for 3-4
minutes before it becomes responsive
With so many tables ,any edits you
do on the edmx take long.
When you are going to use a version
control, comparing 10000 line XML is
quite painful. Think about merging 2
branches each having a 10000 line
edmx,the tables, new association
between tables, deleted associations
and going back and forth comparing
xmls. You would need a good xml
comparison tool if you are serious
about merging 2 big edmx files
For performance reasons we had to
make the csdl,msl and ssdl as
embedded resources
Your edmx should have to be in sync
with your DB all the time,or at
least, when you try to update the
edmx, it will try to sync and might
throw some obscure errors if they
are out of sync.
Be aware that your
entities(tables/views) should always
have a primary key, else you will
get obscure errors. See my other
question here
Things We did/I might consider in the future when using EF
Use multiple edmx by using 1 edmx
for tables logically grouped/linked
together. Be aware of the fact that
if you do this, each edmx should
live in its own namespace. If you
try to add 2 related tables(say
person & address) to 2 edmx in the
same namespace, you will get a
compiler error stating that the
foreign key relationship is already
defined. (Tip: create a folder and
create the edmx under this folder.
If you try to alter the namespace in
the edmx without having the folder,
it does not save properly the
namespace the next time you
open/edit it)
fewer tables in edmx => less heavy
container => good
fewer tables in edmx=> easier to
merge when merging 2 branches
Be aware of the fact that object
context is not thread safe
Your repository (or what ever DAO you use) should be responsible for creating and disposing the container it creates. Using DI frameworks, especially in a web app complicated things for us. Web requests are served from the threadpool and the container were not disposed properly after the web request was served as the thread itself was not disposed. The container got reused (when the thread was reused) and created a lot of concurrency issues
Don't trust your VS IDE. Get a good
XML editor and know how to edit the
edmx file (though you don't need to
edit the designer). Get your hands dirty
ALWAYS ALWAYS ALWAYS (just cannot emphasize this enough) run a
SQL profiler (and I mean each and
every step of your code) when you
execute your queries. As complex as
the query might look, you will be
surprised to find how many times you
hit the DB Example:(sorry, unable to
get code to the right format,can
someone format it ?)
var myOrders = from t in context.Table where t.CustomerID=123
select t; //above query not yet
executed
if(myOrders.Count>0)//DB query to
find count {
var firstOrder = myOrders.First()//DB query to get
first result
}
Better approach
// query materialized, just 1 hit to
DB as we are using ToList() var
myOrders = (from t in Context.tables
where t.customerID=123 select
t).ToList();
if(myOrders.Count>0)//no DB hit
{
//do something
var myOrder = myOrders[0];//no DB hit
}
Know when to use tracking and no
tracking(for read-only) and web apps
do a lot of reads than writes. Set
them properly when you initialize
your container
Did I forget compiled queries ? Look
here for more goodies
When getting 1000s of rows back from
your DB, make sure you use IQueryable and detach the
objectContext so that you don't
run out of memory
Update:
Julie Lerman address the same problem with a similar solution. Her post also points to Ward's work on dealing with huge number of tables
I'm not too familiar with Entity Framework, but I believe it simply generates an EDM file which can be hand-edited. I know I've done this quite frequently with the Linq-to-SQL DBML files that the designer generates (it's often faster to hand-edit them than use the designer for small tweaks).
You know I'd be interested if any developers can provide some insight into this.
Any Entity Framework examples seem to only consist of about ten to twenty tables, which is small scale really.
What about using the EF on a database with hundreds or even a thousand tables?
Personally, I know several developers and organisations that were burned by LINQ-to-SQL and are holding off for a year or so to see what direction EF takes.
Starting from Entity Framework 4 (with Visual Studio 2010), the generated code is outputted from T4 (Text Template Transformation Toolkit) files which you can edit so you have full control over what is generated. See Oleg Sych's blog which is a mine of information about T4. Code generation is not a problem and T4 opens so many perspectives that I can't live without anymore.
I'm currently working on a project where we use Entity Framework 4 for the data access layer, and Scrum as the agile project management method. From one sprint to another, there are several tables added, other modified, new requirements added. When you have run once into each potential EF problem (like knowing that default values from database are not persisted by default in the .edmx file, or changing a nullable column to a non-nullable and updating the designer doesn't change the mapped property state), you're good to go.
Edit: to answer your question, it's EF 4 whose code generation is based on T4 rather than T4 supporting EF. On EF 3.5 (or EF 1.0 if you prefer), you could in theory use T4 by writing them from scratch, parsing the EDMX file in the T4 code and generate your entities. It would be quite a lot of work considering all of this is already done by EF 4. Plus, Entity Framework 3.5 only supports one type of entitiy, whereas EF 4 as built in or downloadable templates for POCO entities (that don't know anything about persistence), Self-Tracking Entities...
Considering Entity Framework itself, I think it was lacking many features in its first release, and while usable, was quite frustrating to use. EF4 is much more improved. It still lacks some basic features (like enum support), but it has become my data access layer of choice now.
Say you had to quickly build a data-entry UI that works in a web browser, which must interface with a business layer, which must interface with a data layer.
You want to connect only to business objects, not directly to the database.
Most of the views of the UI will be simple CRUD operations, with edit/update happening within a grid.
But some of the screens will be more complex, representing many-to-many relationships.
What's the fastest way to achieve this in ASP.NET?
(Note: speed of development is high priority, code quality and re-usability are low priority.)
Entity Framework + ASP.NET Dynamic Data?
If speed of development is the main priority, then go with what you know.
For example, if you know ado.net/enterprise library then go with that. If you know Entity Framework or LINQ, then go that route.
Without a summary of your skills, it's going to be impossible for anyone to tell you the fastest way to get something up and running.
I've written a lot of little business editors like this for my company in the same manner, get it to work quickly, if it's used or needs to be improved, I deal with that later.
Start up a new asp.net project. Add a class library to the solution and reference it from the asp.net application.
Asp.Net Application
Use Master Pages and Themes
Use a repeater for the data lists and command buttons for selecting and deleting.
The repeaters work well for inner lists as well, take note of OnItemDataBound and OnItemCommand.
Use Panels to hold the lists and editors, write some logic to control when to view editors and when to view lists.
If the logic is common, then make some base pages that new editors can use and override.
Class Library
Add your business objects
Add a Linq to Sql class and add database objects as necessary.
To make it simple, you could use the some of the time tested controls and objects:
User Interface Layer: GridView for displaying and providing links for editing and deleting data. Clicking on Edit link may open up a new Asp.net web page that holds FormView for inserting and updating records. Use ObjectDataSource to link methods at the Business Logic Layer to Create/Read/Update/Delete records.
Business Logic Layer: Apart from creating CRUD methods, you might need to use light weight serializable data transfer objects to pass data between different layers and a custom mapper to trnaslate data from and to other layers.
Data Access Layer: Linq to Sql might make the data access and manipulation quick and easy.
It depends on the complexity of the application. I would go with Linq to Sql. But then using Linq to Sql does not necessary provide a good abstraction between the business layer and the data access layer. But I find that using Linq to Sql you can quickly retrieve the data out of the storage and display it on the screen.
Also, if you want fast UI then take a look at dynamic data website. That also uses Linq to Sql or Entity Framework.
One question you must think is that if you need good design or RAD.
I just started working on an asp.net / C#.net application that is going to call a number of different procedures. The -only- thing these procedures do is create database table views, and the only thing I want to do is to store the information in variables. Then pick out which columns I want to convert to JSON, and then make a JSON string. I've actually written code for that in C#.net already, which is smaller, but since I switched to asp.net mvc I'm a little unsure if I should keep it or go with the whole Linq thing.
I checked out the Linq --> SQL drag & drop functionality, and that instantly created about 200 lines of code with set & get methods and everything.
So my question is, is it still worth using Linq even for just extracting data? Eventually this data will be fed to a javascript timeline, which is where I was told MVC would be highly useful with regards to Ajax functionality.
Since you are only using LINQ-to-SQL for data retrieval, I can't think of a single reason NOT to fully utilize it. I've been working on an MVC 1.0 project since last April. During that time, I've had to quickly become familiar with a number of technologies, LINQ-to-SQL being one of them. Get comfortable with it, and also look at the repository pattern...you will be very content and things will go relatively smoothly.
Now, when you get to INSERTs and UPDATEs, things are going to get a little more sticky. LINQ-to-SQL is still up to the job, but you'll need to understand how things work internally a little better. I highly recommend "Pro LINQ (Language Integrated Query) in C# 2008" by Joseph C. Rattz, Jr. The sections covering LINQ-to-SQL easily take up over a third of the book with detailed examples.
As far as the JSON objects go, LINQ-to-SQL's biggest contribution is that it allowed me not to have to worry about creating specialized views or stored procedures just to handle those one-off-types of data retrievals. My current project has a database of 65 tables...NO stored procedures. I can do filters, unions, multi-level joins...and it's all maintained in the application. Sweet...
Yes, it's totally worth it!
LINQ2SQL provides you a great subsurface to retrieve and save data to.
However, you'll need to implement your own Repository Pattern as you dig deeper into ASP.NET MVC.
And during the implementation of the Repository and the required (and even custom / webapp-state based) Queries, you'll be very glad to have all the power available at your fingertips that LINQ provides.
LINQ only adds to the available toolkit you can lean on when creating code. Even if you are using LINQ in a trivial way now, implement it, get familiar with it, and take advantage of the power it gives you both on this project and future projects.
Linq2Sql is quiet good for creating select queries. As it is appearing that you need to create JSON objects from database views it will be quiet useful
I'm trying to get a high-level understanding of ASP.Net MVC, and it has started to occur to me that it looks a lot like the original ASP script. Back in the day, we were organizing our "model"/business logic code into VBScript classes, or into VB COM components.
Of course, now we have the additional power of c# and the .net framework classes. Besides the high-level oo and other capabilities in c# and .Net, what are the other major differences between the original ASP and ASP.Net MVC?
There are three main differences: URL mapping, separation of logic from presentation, and strong typing.
URL Mapping
With classic ASP there is a smooth transition from writing HTML pages to writing HTML pages with dynamic content. As with static HTML files, each URL has a direct mapping to a file in the filesystem. The same thing is more or less true of ASP.NET, for what it's worth.
In ASP.NET MVC, each "family" of URLs maps to a Controller object (stored in the /Controllers directory, by default), where each member of the family calls a method when accessed. At the end of each method (typically), you tell it to render a particular view (stored in a folder named after the controller in the /Views directory), which is a lot like a classic ASP page with all of the logic separated out.
This gives you logical and SEO-friendly URLs and groups related functionality together.
Separation of Logic from Presentation
In classic ASP it's common to find pages where a bit of HTML is included at the top, and then a database connection is opened and some things are read from the database while being output to the user, and then some more html, and then another database statement, and so on.
In ASP.NET MVC, your business logic (e.g. validation) goes in the model layer (you can choose from one of several dozen, but popular choices are LINQ-to-SQL and LINQ-to-Entity-Framework), your human interface logic goes in the controller (e.g. populating a State/Province menu based on the Country selection), and your presentation (the actual HTML you can hand to a designer to edit) goes in the view.
Aside from keeping things organized, this helps a great deal with being able to write automated tests for things. You can send a mocked-up object to your view and make sure it looks good, you can send bad data to your model and make sure it complains, and you can make sure that the object your controller sends out to your view is consistent with what it reads from the model.
Strong Typing and Compilation
ASP.NET is strongly typed and compiled. This is a double-edged sword. On the one hand, it will catch a lot of stupid programmer mistakes at compile time. On the other hand it, that means you're left with "infinity minus one" possible errors in your code (unit testing can make it infinity minus some larger number). Also, you'll have to do things like:
if (MyArray.Length > 0)
rather than
if (MyArray.Length)
But IMHO that's a small price to pay for the speed and sanity-checking you get from strong typing.
The bigger downside to compiled languages in a big framework is that deployment becomes much more of a production than it is with something like Classic ASP. You can't just copy a couple of files to the web server to update your app. You typically have to take the webserver down (hopefully you have a redundant pair) and recompile, which can take minutes.
ASP.NET MVC has a lot of plumbing infrastructure: for example, the routing engine which automatically invokes the right controller and action and can extract bits from the URL to pass as action arguments; or the convention-based location of views. It also provides more structure for passing data from the controller into the view (the ViewData object).
Also, crucially, MVC supports view engines. You can write raw HTML with helpers in it, but you can also use view engines like Web Forms, Spark, NHaml, etc. which allow you to write more concise view code, create reusable components (e.g. Web Forms controls), etc. This wasn't possible in ASP Classic.
Classic ASP used VBScript, which does not have classes. It's not object-oriented at all.
Very often with different technologies we can achieve the same
final result.
To create simple sites is almost irrelevant to the choice of technology.
But when you want to make a large complex site the presence or absence of a framework that allows to optimize the code, keep well organized and efficiently divide may play a role
crucial and greatly reduce the work.
ASP Classic does not achieve the same results reached by asp
net mvc.
If we omit the obvious differences between c # vb script I would say that the difference
main is that you can keep your code better organized.
As with classic ASP is very easy to make "spaghetti code and, with asp
mvc, on the contrary, it is very easy to keep everything tidy and separate the code
business logic from display.
Not only that.
Asp Net Mvc seamlessly integrates with technologies such as that EntityFramework
allow a further breakdown and organization of the code.