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.
Related
I am currently in the beginning of designing an MVC application.
While running some tests through a prototype I came across an issue with the way some data is being handled.
Here's a simple DB diagram
When working on my prototype, I noticed that when the Entity Framework builds all of the required models from SQL it creates an ICollection relationship from the Employee_Table to the Job_Position_Link_Table. I cannot access attributes directly in the Job_Position_Link_Table if the view is strongly typed to the Employee_Table. Also I cannot get to the Job_Position_Title_Table as well. I looked into creating a ViewModel for this issue, but cannot find a good tutorial on how to create the ViewModel when you are working with an ICollection. Most tutorials are from a code first approach, and I am dealing with an inherited database.
The other solution I was thinking of was creating all of my Views in SQL and then passing them into MVC.
I am still new to MVC, and was just wondering what the best practice in this scenario would be?
You should never bind your views to EF entities. Instead, create view model classes with required properties and convert the EF entities into these VMs (you can do that manually or with the help of auto mapper). Then, your views can be bound to your view models.
Its the job of controller to build the view model and send it to view engine for rendering. Thus, view must expect a view model ready for presentation.
When using Entity Framework with Code-First, what is the best practice when calling database data?
This is my first time using Entity Framework with MVC and noticed that it automatically builds Models in my DataLayer. I also have the basic Models within my MVC UI which allow me to manipulate and display the data within my Views. I currently grab the data using my Workflow layer, and then AutoMap the Database Model to my UI Model to display the data.
Is this the best practice? Should I be using the Entity Framework Models instead of my UI Models? Or this even possible to do cleanly?
Any information on the matter would be appreciated.
It's up to you really. If you like to re-use the same EF entities for your view models as well; go ahead. Personally, I prefer not to. This is because you normally end up adding a bunch of properties to the class that have nothing to do with what's stored in the data and yes; I know you can use the NotMapped attribute like this:
[NotMapped]
public string MyExtraProperty { get; set; }
but I prefer not to. Additionally, you end up adding [Display] and other attributes to your properties and before you know it, you've got something decorated with both data specific and UI specific attributes and it can get messy if you're not careful.
So for me; I have the following:
Domain Entity
View Model
Service/Facade/Repository
Controller calls repository to get the domain entity and converts it to a view model for displaying.
I find that to be a cleaner approach, but maybe that's just me.. the most important thing is to just choose one way and stick with it for the sake of consistency and clarity of code, but either method is acceptable.. "whatever floats your boat" as they say...
The POCOs created by EF are supposed to be used as your model. The general idea is that you have EF providing access to your database. You query EF using LINQ and/or extension methods and end up with an object or collection of objects that you display on your UI by binding them in WPF. That is of course if you're using WPF as opposed to the older WinForms. I can tell you from experience that it's a very streamlined process once you become familiar with the technologies. That's how a very basic setup would work.
A more advanced way of going about it is adding architectures like Model-View-ViewModel (MVVM) and possibly the repository pattern into the mix at which point you get better separation of code and presentation at the cost of increased complexity.
I don't know what flavor of MVC you're using and how it can be made to intermingle with the above, but if you want to know more about how EF was envisioned to work you should look into the technologies I've listed above.
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.
I have an application that I want to migrate to ASP.NET MVC. There are few stumbling blocks that I am not able to clear.
I am using the following components
Linq to Entities
MVC with Razor
Now I have three major hurdles.
The sql query is quite complex - I want to use it as it is (without Linq )
How to create a view that will display data from this query's resultset
the query involves joins on tables across multiple databases (though on the same server ) - what is the best approach to make it pure-linq in future.
I'm still learning the Entity Framework myself, but hopefully my answer will help you out a little with some advice and starting points.
If you have a complex sql query that you want to leave intact as is, your best bet is to add it as a Stored Procedure in your Database. You could then add/call the Stored Procedure using the Entity Framework. You can set up the model to use a stored procedure.
Using my suggestion in #1, I'd recommend you simply build a custom object to store the data in the structure you need it to be in. In your controller (or however you have your project set up for data/business logic) you can populate the object by using EF to call the Stored Procedure. You could then create your view and strongly type it against that object/model and display it in whatever manner it's needed in.
As for this question, I am not sure. However, I did do a quick search and hopefully this thread may help point you in a direction. EF4 cross database relationships
I'm new to MVC and even though there is a lot (and I do mean a lot) of information out there that is very useful - it's proofing very difficult to get a clear understanding on how to achieve my exact requirements with MVC 2.0.
I would like to set up a solution as follows:
Provide a web UI using an MVC 2.0 project.
Use Linq to SQL classes project for data persistence.
I have a two separate code modules that will need to access the above Linq to SQL model - so I won't be able to include my Linq to SQL model directly in the MVC project itself.
Also I have a Business Logic layer in front of my Linq to SQL project.
My questions are:
How do I set up the Model part of my MVC application to point to my Linq to SQL project via my BLL?
How do I perform web app validation? Can I use MVC 2.0 Model Validation? If not what are the alternatives?
Finally (and slightly aside) - What is the ViewModel and how does this differ from the Model?
So many questions. But this is an exciting new technology and data access issues aside, everything else I've got to grips with very quickly and I think MVC 2.0 is fantastic.
Thanks for any pointers you can provide.
How do I set up the Model part of my
MVC application to point to my Linq to
SQL project via my BLL?
Typically you'd use a repository pattern for this. Your controller has a reference to your repository - the repository returns your domain objects from your database. The MVC app has no knowledge LINQ to SQL exists.
How do I perform web app validation?
Can I use MVC 2.0 Model Validation? If
not what are the alternatives?
Put view models in your MVC project. These view models may closely align with your domain models but their concern is to be the presentation model. Put your data annotations for validation on these view models - the MVC framework will automatically ensure validation occurs on these view models decorated with data annotations. It's pluggable so you could use alternatives - but with MVC 2, it's baked in fairly well and this includes client side validation.
Finally (and slightly aside) - What is
the ViewModel and how does this differ
from the Model?
I partially answered this one above. the shape of your domain models may not be the shape you need to display your views - view models are great to bridge this gap. Additionally, even if the shape does match exactly - view models are still a good idea so that you can put UI validation code there and other presentation meta-data on them (since you do not want anything related to presentation logic on your domain model).
Here's link for view model patterns.
Hope this helps.
You can add a reference to the objects exposed from your BLL assembly and use them as your Models.
When you want to add validation to classes that are generated use buddy classes.
A ViewModel is a custom-shaped aggregate of Model data. There is exactly one per View, as the ViewModel's purpose is to surface exactly the data needed by a particular View in a convenient and concise way.
An example might be a View that contains both Order and OrderDetail information. A ViewModel can hold internal references to the repositories and business objects for each type. Properties of the ViewModel merge together the data from these objects.
ViewModels will be useful in your case also because you want your Models to be in a separate assembly. You can apply the DataAnnotations to ViewModel properties for validation. You would make the "raw" business object models internal properties of your ViewModels, and expose public methods to retrieve and persist data.