ASP.NET-MVC data/model best practices for a newb - c#

I am quite new to ASP.NET MVC and MVC in general. Moving from the old school "spaghetti" design practices to WebForms was a big change, but this seems bigger (but better) in my mind.
I have some questions regarding data specific tasks.
For the sake of simplicity, say I have a database table called PIN with the column structure of PinId INT, Value VARCHAR(50) and another table called Entry with the columns EntryId INT, PinId INT.
I have an MVC view that takes in a string value as a PIN code.
The goal is to insert a row into the Entry table. To do this, I must lookup the corresponding PinId to the provided Value.
My question would be, where do I perform this lookup of data. I can easily do it in the controller where I am performing the insert of a new Entry object but is that right? Should this lookup be performed in the Model somehow?
In addition, I am following the instructions and practices outlined in WROX's Professional ASP.NET MVC 1.0. I have created a DataRepository class which handle all of my DB heavy lifting, and am utilizing the validation class as described in that book.
Any insights would be welcomed as I am a true newbie to MVC.
Cheers and thanks stackers!

Take a look at ModelBinders. This allows you to define how bind inputs from the data you are sending to your action to your Model objects. Your Action can also just take an argument of the type you want to save, and in your ModelBinder, you can do some lookup against the repository, etc.
There are many good blog posts on this if you do a search, now that you know to look at ModelBinder. Scott Hanselman has a good basic one:
http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx

Never place search, add, update, delete code within a controller. Actually, there should be next to no code in the controller.
In the MVC world the controller is simply a means of getting a model from the view to your business layer and vice-versa. The aim is to have as little code here as is possible.
If you can use Linq2SQl then this would be a great place to put the entities. You can then use your data repository to do not only the heavy lifting, as you put it, but also all the other little things.
Linq2SQL will create a partial class. So, you could create another partial class which will do the CRUD and search work for you.

Related

How to differentiate between Model and Entity?

I have already read A LOT but I still struggle to understand the question of this post. I am building (learning how to build) my own web application using .Net Core Framework, and also I'm using MVVM architecture, and this terms are crucial for me to understand what I am doing, namely, the Entity Framework. If someone could explain them to me with some examples, it would be perfect. Thank you in advance guys.
There is a simple thing here.
A model is a model for a view etc. - they often contain only partial data compared to entities, data from multiple entities or additional fields that are just there to be output. I.e. a model may have a collection of possible values for another property so that the view can then show a dropdown to select a value.
An Entity (in Ef terminology) represents (simply said) data in a table or view (though they can be a little different). There is no concern about presentation here.
Within MVVM you have 3 components:
the model
the view (speaks for itself)
the viewmodel
In entity framework, you have:
entities
So how does it relates?
The Entity
In general it's "a thing" which has a right to exist. Within a EF context this is often referred to as a table.
ViewModel
It's a model, tailor made for a view. Ideally it contains a set of properties and some commands. Through binding, you can update your view by setting properties. The text of a label for example.
The Model
Now the fun starts; the Model is an object, possibly containing data and some of the business logic.
Basically, this could be an entity, but it doesn't necessarily have to be. As a matter in fact; depending on the size of your application don't (or do) want to mix your data layer with your business logic.
Wikipedia states it beautifully:
Model refers either to a domain model, which represents real state content (an object-oriented approach), or to the data access layer, which represents content (a data-centric approach)
So, the entity can be your model, but in larger applications there is quite often a layer in between to separate the "business" language from the data layer language.
Note; if you put an API on top of things, you might also want to dig into the DTO.
Ok so through the answers given and with further reading + outside help I have reached my own conclusions:
Entity
As Stefan said, it is a Table in a database. It is a .Net object that is represented in a data base. For example, a Person class with the fields firstName and lastName will be a table in a database with the columns firstName and lastName.
Model
Things become spicy here.
This is an object that contains the data that will populate a view (for example, may be a JSON that angular will use to generate an HTML, when using MVVM arquitecture). Another very important topic to mention is that the model is created with: entities (one or many entities may be used to create the final model) plus business logic applied by the application(although it is not mandatory). The application may only send "us" part of the total data which is avaiable to it. Take an example: Facebook. When I request my profile, it contains My name, a photo of myself, etc. But it does not contain, for example, my ads preferences! So my application (applying business logic) will cross information and generate the Model, which can also be viewed as a contract to be honored, containing certain data that MUST be there in order to applications in the client side function correctly (for example, some objects in a JSON file must be there) so Angular constructs the HTML (View) with the data from the model.

Client based Table/Models

I'm new to MVC, I only done a basic tutorial with a standard application for editing an existing table, adding rows, view it, etc.
So there was a static view, static controller and a static model, which represented 1 table in the database.
Now I wonder how should that work, if I don't know yet, how the model is going to look like.
In my case, the client can first create a table, where he defines, which rows and what datatypes, etc. and then he can edit the table.
Is there a standard way for dynamic models, or is mvc the wrong way for this?
MVC works fine for this. With MVC, I just split each necessary bit of code up into the three categories. So try to think in an "MVC" Way.
The logic that is needed to connect to the database - Definitely a Model.
The displaying of the data in a structured table - Definitely a view.
The communication between the data gathered with the logic, and the displaying of that data - Definitely a controller
The idea of MVC is to separate the back end logic from the displaying of said logic. This helps to separate the two distinct parts of your project, and is generally considered good practice.
Hope this will help :)

Why do most ASP.NET MVC examples access the database directly in the presentation layer?

Most of (nearly all?) the examples I find on how to set up an ASP.NET MVC project are accessing the database context directly in the controller.
Like this for example:
public class MoviesController : Controller
{
private MovieDBContext db = new MovieDBContext();
//
// GET: /Movies/
public ViewResult Index()
{
return View(db.Movies.ToList());
}
I also know that there are a lot of controls (at least for the aspx view engine) that you can bind to a table in the database directly as a data source, so that it automatically displays the data.
To me this feels weird and I would like some kind of separation between the presentation layer and the database. Some kind of business layer and/or data layer that maps data from the database to view models, before using them in the view. Is it just me or are the examples all like this because it's easier to do? Is there some great gain that I'm missing? I guess it's a bit faster, but it just feels like I shouldn't use the same models in my database as in my views. I finally found an example that feels more right, where the database models are separated from the view models. But it's one example of a hundred.
What are your thoughts on this?
I understand your concerns as I have the same. It's really a pity that most of the examples out there are not using view models. Because of this people are struggling a lot when they start implementing a real application that differs from the most trivial examples seen in those articles.
As far as directly accessing the database from the controller, I don't think that this is such a big concern. You really don't need to implement lots of layers of abstraction if you don't need them and if they don't bring any additional value to your application. Jimmy Bogard wrote an excellent blog post on the subject of limiting your abstractions.
Most MVC tutorials teach you how to do it simply because it can be done, and that the explanation of the Controller usually comes before explaining the Model.
Take the Movie App tutorial for example - http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3
The majority of these tutorials first teach you how to display data using on the view, then using the controller to display in the view, then entering the data into the model and directing to the view via. the controller.
It's to keep the examples simple and focussed on the subject at hand.

Need direction in creating an application which generates a crud form

I was wondering if anyone knew of any way i can implement an application which will do the following.
Allow a user to specifiy a connection string to a sql db
Allow a user to specify a table in the db
Allow a user to specify columns from the specified table
Generate Views, a Controller with Crud methods, & Data access code on the fly for the specified table columns in a subdirectory on the current web app.
I'm aware that there are apps that currently do this (such as sharepoints list creation stuff), but i'd like to see how this was accomplished and recreate it for my own learning purposes.
Thanks alot for any help
Take a look at Microsoft's take on scaffolding, also, some time ago I was developing a taxonomy app and found this meta data model in codeproject
Edit: another cool SO link
Have you check out SharpArchitecture?
Anyway I fiddle with MVC 2 based AutoCrud when I'm not saving the world from aliens so I can give some pointers and point to things to check out:
Become familiar with how MVC 2 can auto scaffold up your edit screens
Understand that you'll have to pass "meta" information about your models somehow. In MVC 2, this is called ModelMetadata.
Tackle how to display related or associated models in aggregate root or parent screens
Learn how to generate code, and inspect ddl schema or meta information with T4 templates.
Thats all I can think off for now. This is not an easy task and a comprehensive answer is probably enough to fill a book.

ASP.NET MVC Best Practices

I come from the WPF side of the world and I am used to using the MVVM pattern quite a bit. I am attempting to learn MVC and am having a little bit of difficulty trying to understand where my boundries are in MVC. Here is my scenario:
I have 3 objects, Parent, Child and GrandChild. These are custom objects, not using the built in model stuff from MVC. I have a good handle on validation stuff. I have a good handle on how to get and populate my objects. But, I am struggling to find best practices on what to do with Controllers. What should my controller be responsible for? For example, should I have one controller that understands how to CRUD Parent, Child, and GrandChild? Or should those be separated? If they should be separated, how should I do that if, when I am looking at Parent, I want to see a list of Children.
Controller is used only for controlling the flow of the request-response. So, in your example, controller should never know how to CRUD them. CRUD logic should be wrapped in a Repository class of the model.
Take a look at the Official Nerd Dinner example and I personally love this part the most.
The Nerd Dinner app is a clean cut example. I agree with pushing CRUD to a repository, and in general, using the controller only for control flow.
However, in my experience with ASP.NET MVC (right or wrong), the controller ends up doing a lot of rearranging of the data before handing off to the view, and vice versa when accepting an object model as data from a form post. But again, it is just making a translation between what the View needs and what the Model needs.

Categories

Resources