EF + SQL Server: Code First or Database First - asp.net-mvc

I have a system written in ASP.Net 2.0 Web Form. The framework that talks to MySQL Server is really cool. It reads all controls inside the server form tag or panel and does CRUD operations on the target table.
When I create the CRUD page, I just need to create the table in database user{id,name,password,createdate} and I just need to use id to be the exact column name in the table. The controls can be input/select/option/chekbox/textarea or even FCK Editor or CK Editor on the page. The framework loops through all the controls inside the Panel and save/edit/delete. If I want to add some new fields, email and mobile, I just need to add two controls on the page and add two more columns in the table. That's it. I don't have to change anything in page.aspx.cs file, Entity Layer, Business Layer or Data Access Layer. It is VERY easy to implement and maintain.
We want to upgrade the system to use ASP.Net 4 MVC3 with Entity Framework CT5. We will rebuild the whole system from the scratch. I was hoping some experts here could give me some pointers. I found the following two options to rebuild the system.
1. Code First
Our new system will do the exactly the same operations as the above framework. It will loop through all Request.Forms data and map them with its associate table in the database and save/update/delete all the data. To do this, view will post the form data, controller will accept the values with the Entity classes and save them to the database via EF. I still need to create ViewModel class to display data on View. If there is any change like adding email and mobile fields to user page, I still need to change three places view, entity(domain class) and ViewModel. I don't have to change anything in database as EF will automatically run ALTER TABLE to add two new fields. I still cannot figure out how to minimize the needs of both entity and viewmodel classes.
2. Database First
I really do not prefer this way but I will if this solution provides more flexible operations. I will create the columns in database, the system will dynamically create the ViewModel(I am still figuring out how to do that) reading all columns in the table, and display data on the page. When the view post data it needs to dynamically create the entity class and save the changes to the database.
EDIT:
Reasons of upgrading the current system.
We want to use the power of new features in .Net 4, Linq, Entity Framework, unobtrusive javascript library, easifer to work with JSON data, Remote Validation(We can use RequireFieldValidator, RegExValidator in current system but they are limited, for eg: validation on input checkboxes and option), duck typing with var and interface.

Our new system will do the exactly the same operations as the above
framework. It will loop through all Request.Forms data and map them
with its associate table in the database and save/update/delete all
the data. To do this, view will post the form data, controller will
accept the values with the Entity classes and save them to the
database via EF.
Someone please slap me if I'm missing something here, but these statements seem contradictory to me. If you want a system that will automatically parse the Request.Forms data and map them directly to a database table, then why would you need to use Entity Framework (or any other kind of middleware) at all? The point of EF, or any ORM, is to create a meaningful collection of conceptual data objects that represent your system's nouns. You then operate on those nouns, affecting their properties or accessing their behaviors, and let the ORM figure out how to map them to the tables + columns.
To answer your question, it sounds like you want the easiest solution, meaning the one where you have to write the least amount of code. If that is a correct assumption, then you might want to go with Database first. You can have EF generate your entity classes, but like you said, you will still have to either manually create viewmodel classes or come up with some kind of AOP (using T4 maybe) to generate these for you. But anytime you give a tool the power to generate something for you, you lose control over it.
I prefer code first / conceptual model first, but I also like to have complete control over everything in the application (aside from infrastructure concerns which can be delegated to tools and frameworks like AutoMapper, EF, T4MVC, etc). Yes, it is more work, because I have to create the entity classes, the viewmodel classes, and the views, (and controllers, and action filters, and html helpers, and rrrvrything else). If your domain is one where you can just map text boxes straight to database tables & columns, then maybe this would be overkill for you.

Related

How to modify CRUD operations with Entity Framework in .NET MVC application

I need to work out how to do CRUD stuff in an MVC application, passed to me by a former colleague (I don't have any other info, just the application and the database). So I can see there is Model1.edmx and the model browser that contains MyApp.Model>EntityTypes>MyTable representation, and MyAppModel.Store that contains a representation of the table, and the Model1.Designer.cs file which has methods that look like they must be CRUD related (e.g. OnLastNameChanging, OnLastNameChanged). I can run the application and insert and update records to a db table.
What I need to know is where / how do I code other CRUD operations and use Entity Framework to work with WHERE clauses, and do stuff like update another record in a table depending on the value of a given field in the record being inserted or updated.
I've worked with MVC on one other small project but haven't really worked with entities. I'm used to the WebForms / ADO.NET / stored procedures way of doing things.
Any help gratefully received.
Happy new year!
I guess you are using database first approach.
some useful links for Code first approach:
http://www.codeproject.com/Tips/793159/Code-First-Approach-in-Entity-Framework-using-Data
other for database first approach
http://www.aspdotnet-pools.com/2014/08/insert-update-delete-operation-in.html
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

Workflow with MVC 4 - EF 5 - SimpleMembershipProvider

So I want to build an application with MVC 4 and Entity Framework 5. I've build simple applications before, but now I need some security around my current effort... I have some confusion / questions that I was hoping someone could answer;
First... Using the MVC 4 Internet Application Template it implements SimpleMembershipProvider. I have read every primary article about modification, implementation... However, this uses a Code-First implementation...
Problem: I have an existing database that I would like to import the scheme for to an EDMX database first approach... How do I implement the MVC 4 Simple membership provider when my database ties tightly and directly into the user table (userid)?... I know I can use my own user table as long as i designate the userid and username fields as documented... Will this affect the provider, or the existing "AccountController" code? Will these need to be modified?
Second, what I am looking for is a workflow with this architecture... I am "old school" mostly database first approach... My project is a huge WIP (work in progress). I have a foundation, but will need to expand as needed... Can someone provide some insight into database first vs other approaches when there will be quite a bit of change management occurring?
you can still use Code First to map to an existing database. You may need to explicitly map properties to table columns because the mappings do not follow the default conventions, but that doesn't prevent you from using Code First.
When transitioning from DB first to another mindset. Focus on how the objects interact with each other. then, at some point you will save the state of the objects after they interacted. This is where the ORM comes into play. detects changes and executes the necessary SQL statements to persist the current state of the objects.
Think of the database as just another storage container. In theory it could be replaced by another persistent storage mechanism (document db, file, persistent hash table, in memory list, etc.). In reality it's not that simple, but the idea of treating the DB as just a simple storage container helps to break away from the monolithic database concept that is/was ingrained into most devs.
But don't loose perspective of the design either. If it's a simple forms-over-data app where you will be adding features in the future than keep the design simple. than don't try to totally abstract the DB away. you know it's there and the relationship to the UI is almost 1:1, so take advantage of that.
In it's simplest form separation of concerns can be achieved by using the MVC controller to manage the interaction between the model (mapped to the DB via ORM) and the view (razor templates) my personal preference is to keep ORM out of the views so I typically query the database, map the domain model to a viewmodel and then pass the viewmodel to the view.
Again if it's a simple application and screens map directly to the database than viewmodel are probably overkill.

ASP.NET MVC Database Views

Quick question about database views. Am I right in assuming that I can create a database of view of various tables and connect them how I want etc and then when I do queries, add, edit delete etc then MVC will figure it all out for me without needing to do any complex SQL in the controller or repository?
Odd question but just wanted to make sure my assumption was valid. Cheers
Unfortunately, MVC will not figure it all out for you, you'll still need to write the SQL code (or use an ORM framework) to communicate with the database.
What MVC gives you with it's architecture is a clear separation of responsibilities:
Views are responsible for displaying data and should be as simple as possible (i.e. little to no logic in them)
Model(s) contain the business logic and rules
Controllers are responsible for passing data between the Model and the Views.
What you are looking for is Scaffolding. In .net MVC I can't think of any tools which do this for you directly against the database. They all require either as Russ said an ORM i.e. Linq To SQL or Entity Framework (EF).
http://msdn.microsoft.com/en-us/library/cc488540.aspx
The closest you could get would be to use Database First model generation and then put the necessary MVC templates/views/code on top.
A database view is read-only so you will not be able to perform write operations on the view. You can however create a model from a view and display your data as defined from the view. If you are using an ORM solution such as ADO.NET Entities you can instantiate an object and add the child objects to it and be able to save the final result in a single transaction as well.

How to add a table to the EF4 Context dynamically in code - No Code First

We run a series of reports every 6 months and store the results to tables that can be queried/viewed at any time in the future. Depending on the cycle either two or four tables will be added. They have a standard naming convention of yyyy_mmm_Table_x.
Our website is built using ASP.Net MVC2 and the database is modeled using EF4 using the standard model designer, not Code First.
I would like to be able to dynamically add the report tables to the EF4 context at runtime. I don't want to have to manually add them to the model using the designer, otherwise every reporting cycle we have to update and recompile the model just because we added the extra reports. That would be a maintenance headache when nothing else has changed.
I can get a list of the available tables simply by querying sysobjects. If I could get this list and add the tables to the context when the site started up then I could use something like the Dynamic LINQ library to query against them depending on which table the user selected from a dropdown.
I can't use EF4's Code First out of the box because that would force me to create concrete classes for the tables and that would just be the same maintenance headache. I suspect I could use the same strategies the Code First framework uses to dynamically update the context, but I haven't looked at this library at all and I'm hoping someone familiar with it can point me in the right direction.
Otherwise I think I would have to drop back to ADO.Net to handle this area. That may be the best and simple way so I guess I'm looking for comments. I'm not a zealot so I don't need everything to be in LINQ and EF4. :) But it would seem to be a little cleaner and consistent, especially if it allows me to make use of Dynamic LINQ. But sometimes the old way is just simpler.
So, if you have any suggestions or comments I would love to hear them.
Thanks!
Even with common EF you still need new data type for each table because when you map the table you need new ObjectSet of new entity type to be able to run queries. As I know it is not possible to map two tables to the same entity even if table structure is absolutely same.
All runtime mapping is stored in MetadataWorkspace prepared by EntityConnection. So if you want to play with it you can start there but public interfaces of these classes don't look promising.
I guess you want to run Linq-to-entities on these tables so using Stored procedure returning data from correct table based on data parameter is probably not an option.
You should use common ADO.NET for this.

Can EF4 generate POCO for me, or do I have to write them myself?

I've been playing about with the Entity 4 framework lately and it's pretty nifty. I've setup a class called Customer.cs with some properties like Name, Address etc. I also have a class called StoreEntities.cs which binds these back to the database through DbSet. It works fine and I can pull all my customers from the database.
The problem is every tutorial I come across on the internet generates their classes by hand. What I mean is, they all say something like "Now I'm going to make a new class called Orders with the following properties" and then proceed to write it out. That might be ok if I was starting a new project, but I'm porting over my old website so I have upwards of 20 tables in my database. If I go through and write all these out by hand I'm going to be there all week :D
Plus I'm not sure what would happen if I made some changes to the database (since I would have to go back through and update all my classes by hand).
I was hoping EF4 would have something similar to a Class Diagram, where I can point it at my database and have it generate a bunch of classes for me based on that.
I'm a little lost on this. Am I going about this the right way?
You should take a look at the ADO.NET C# POCO Entity Generator. With that you should be able to generate your model from your existing database and T4 templates will generate your POCO classes based on your databases tables, etc.
Here is a link to MSDN that explains how to Update Model from Database using the Update Model Wizard.
There are two ways to achieve what you want. Both start from adding new item to your project. In the "Add new item" window select "ADO.NET Entity Data Model". There you will have two options. One to generate your model from existing database and second to create model manualy in designer. If you choose first one you can simply drag and drop tables from server explorer to design surface and all your entities and their relations will be generated for you automaticaly. Also you can modify that generated model later.

Resources