Creating custom model using other models in ASP.NET MVC - asp.net-mvc

As the title suggests I have two models Products And Orders which are actually two table in my database and I have used a LINQ to SQL class to create there models. Now I wan to create a model named "OrderDetails" which will have properties from both the model like product name and id from product and Order number from orders something like this. An then I want to create a view from this custom model and from which I want to add "CRUD" operation. What should be my approach. And in many scenarios I may have to use data from more than 4 models. Please help. I'm wondering helplessly and I have only two days experience in ASP.NET MVC.

I'd go this route:
namespace Models
{
public class OrderDetails
{
private Products _products;
private Order _order;
public OrderDetails(Order order, Products products)
{
_order = order;
_products = products;
}
// now expose whatever fields or logic you need.
// for instance:
public Customer OrderCustomer()
{
return order.Customer();
}
}
}
However, before you go around making all of these new models, are you sure you need them? Can you simply use two instances, either passed around separately or in a Tuple? You can get some useful abstraction here, but if you don't need it, keep it simple.

Linq to SQL does not support custom mapping to the extent that you're looking to do. What you'll want to look at is a full ORM. I highly recommend nHibernate, but Entity Framework, if you must, will do what you want.

Related

With regard to design patterns, why not just extend the Entity Framework classes with the business logic?

I've got an ASP.NET MVC application and am looking at ways to improve readability, testing, etc. Currently, much of the business logic is in the controller and I would like to move this to another location.
Here's one idea I have been looking at using: Entity framework creates entity classes for me (e.g. Product, Customer). Why not just create partial classes to store the business logic? Here is an example:
public partial class Product()
{
public static List<Product> GetGreenProducts()
{
using(MyEntities db = new MyEntities())
{
return db.Product.where(p => p.Color == "green").ToList();
}
}
}
Then, in the controller, I can do this:
public class ProductController : Controller
{
public ActionResult GreenProducts()
{
return View(Product.GetGreenProducts());
}
}
This approach seems 1) Very simple 2) Very clean 3) would allow for easy unit testing.
I think this is a relevant pattern. Can anyone identify any problems with this, or other thoughts?
There are two questions being asked here:
Why not extend EF classes with business log (as opposed to Controllers)?
Simple. Because business logic should not be coupled to EF anymore than it should be coupled to Controllers.
Essentially (and this is my interpretation of the OP's comment), why not put CRUD operations in EF as opposed to Controllers. Sample method given: UpdateLastModified does it belong in EF or a seperate Service?
UpdateLastModified is already far too coupled an example to begin with. You should not create a method to update a column on an entity. Do you also need UpdateCreatedBy, UpdateName, UpdateId? I sure hope not. EF gives you all the tools necessary to perform such trivial tasks.
The ProductService should be concerned with middle tier concerns, whatever they may be. Things like projecting the ProductEntity -> ProductDao and what have you. ProductService.UpdateLastModified should not exist.

Best practices with DTOs in ASP.NET MVC Entity Framework

What's the most preferred way to work with Entity Framework and DTOs?
Let's say that after mapping I have objects like:
Author
int id
sting name
List<Book> books
Book
int id
string name
Author author
int authorID
My DTOs
AuthorDTO
int id
sting name
BookDTO
int id
string name
int authorID
Since author can have a lot of books I don't want to retrieve all of them, when for example I'm only interested in authors.
But sometimes I might want to get few authors and filtered books or all books.
I could go with multiple queries AuthorDTO GetAuthor(int id) List<BookDTO> GetBooks(int authorID). But that means several accesses to database.
The ways I see it:
If I had in AuthorDTO field List<BookDTO> books the job could be done. But sometimes I would keep this list empty, if for example I listed only authors. And that means some unconsistency, mess and a lot of details to remember.
Return Tuple<AuthorDTO, List<BookDTO>> it might be a bit confusing.
Define new DTO.
AuthorAndBooksDTO
AuthorDTO author
List<BookDTO> books
The problem with sticking to a sinlge AuthorDTO and selectively filling the List is that you are now forced to keep track of where that DTO came from. Is the list of Books not hydrated, or does this Author simply have no books? Do I have to go back to my controller and call a different method to get a different state of the same DTO? This lacks clarity from the consumer's standpoint.
In my experience, I've leaned the way of more DTOs instead of trying to re-use a set of basic DTOs to represent multiple different sets of data. It requires a bit more "boilerplate", having to set up a whole bunch of similar DTOs and mappings between DTO and Entity, but in the end the specificity and clarity makes the codebase easier to read and manage.
I think some clarification of the issues involved will actually solve your confusion here.
First and most importantly, your entity classes are DTOs. In fact, that's all they are. They're classes that represent a table structure in your database so that data from queries Entity Framework makes can be mapped on to them. In other words, they are literally objects that transfer data. The failing of Microsoft and subsequently far too many MVC developers is to conflate them with big-M Models described by the MVC pattern.
As a result, it makes absolutely zero sense to use Entity Framework to return one or more instances of an entity and then map that to yet another DTO class before finally utilizing it in your code. All you're doing is creating a pointless level of abstraction that adds nothing to your application but yet another thing to maintain.
As far as relationships go, that's where Entity Framework's lazy/eager loading comes in. In order to take advantage of it, though, the property representing the relationship must follow a very specific convention:
public virtual ICollection<Book> Books { get; set; }
If you type it as something like List<Book>, Entity Framework will not touch the relationship at all. It will not ever load the related entities and it will not persist changes made to that property when saving the entity back to the database. The virtual keyword allows Entity Framework to dynamically subclass your entity and override the collection property to add the logic for lazy-loading. Without that, the related entities will only ever be loaded if you explicitly use Load from the EF API.
Assuming your property is defined in that way, then you gain a whole world of abilities. If you want all books belonging to the author you can just interact with author.Books directly (iterate, query, whatever). No queries are made until you do something that requires evaluation of the queryset. EF issues just-in-time queries depending on the information you're requesting from the database. If you do want to load all the related books at the same time you retrieve the author, you can just use Include with your query:
var author = db.Authors.Include(m => m.Books).SingleOrDefault(m => m.Id == id);
My first question would be to ask why you are creating DTO's in the first place? Is there a consumer on the other end that is using this data? Is it a screen? Are you building DTO's just to build DTO's?
Since you tagged the question as MVC i'm going to assume you are sending data to a view. You probably want a ViewModel. This ViewModel should contain all the data that is shown on the View that uses it. Then use entity framework to populate the view model. This may be done with a single query using projections or something complex.
So after all that blathering. I would say you want option 3.
Just like the others said, for clarity reasons, you should avoid creating "generic" DTO's for specific cases.
When you want to sometimes have authors and some of their books then model a DTO for that.
When you need only the authors then create another DTO that is more suited for that.
Or maybe you don't need DTOs, maybe a List containing their names is enough. Or maybe you could in fact use an anonymous type, like new { AuthorId = author.Id, AuthorName = author.Name }. It depends on the situation.
If you're using ASP.NET MVC the DTO you'll want is in fact a ViewModel that best represents your page.
Based on what you've described, you're view model could be something like this
public class BookViewModel{
public int Id {get;set;}
public string Name {get;set;}
}
public class AuthorViewModel{
public int Id {get;set;}
public string Name {get;set;}
public List<BookViewModel> Books {get;set;} = new List<BookViewModel>();
}
public class AuthorsViewModel
{
public List<AuthorViewModel> Authors {get;set;} = new List<AuthorViewModel>();
//add in this class other properties, like the filters used on the page...
public void Load(){
//here you can retrieve the data from your database.
//you could do like this:
//step 1: retrieve data from DB via EF
//step 2: fill in the Authors view models from the data at step 1
}
}
//and in your controller you're calling the Load method to fill you're viewmodel with data from db.
public class AuthorsController{
public ActionResult Index(){
AuthorsViewModel model = new AuthorsViewModel();
model.Load();
return View(model);
}
}

Should I map my MVC3 Models and my Entity Framework Models and if; how?

I'm learning as I go, so I'm not familiar with all of the concepts behind EF and MVC3. I have an app where my EF Models === MVC3 Models, but I also have some aggregate ViewModels. I call things like Person dude = Person.Get(id); in Controllers, where Person is an EF model generated from a database, which I extend with my custom methods, such as dude.GetSiblings();
What I want to do now (if you don't tell me that this is a bad idea) is to move the EF code into another assembly, create yet another assembly with new simpler non-entity models that I can feed to my views and somehow (if possible) serialize and move around as JSON.
The problem is I don't know how. If I move my EF models to a different project (like a separate DAL), how would I create second models that map to Ef models? Wouldn't that cause a lot of repetition if I had code like int id {get;set;} string name {get;set} on both the EF model and the MVC3 model? In my ViewModels I simply use the entities directly like class ViewModelX { Person person; List<Post> posts; int something; } - but that is simply a packaged set of entities rather than a model, isn't it?
What about methods like GetSiblings? var list = dude.GetSiblings() in Controller and public List<Person> GetSiblings() { return this.EFPerson.GetSiblings(); } in MVC3 model? I'm getting very confused as to what goes where. When googling around, I really only found advanced and very beginner tutorials - or maybe I just don't know what to look for so I kindly ask for your assistance!
If I move my EF models to a different project (like a separate DAL),
how would I create second models that map to Ef models?
The view models reside inside the ASP.NET MVC application.
Wouldn't that cause a lot of repetition if I had code like int id
{get;set;} string name {get;set} on both the EF model and the MVC3
model?
Yes, it will cause. That's what View Models are intended to do. To contain the data that the view needs to work with. Where does this data come from doesn't really matter. You could use tools such as AutoMapper to automate the mapping between your domain models and view models.
What about methods like GetSiblings? var list = dude.GetSiblings() in
Controller and public List GetSiblings() { return
this.EFPerson.GetSiblings(); } in MVC3 model?
Here's how a typical controller action might look like:
public ActionResult SomeAction(int id)
{
// fetch an instance of the domain model:
var domainModel = DomainLayer.GetSiblings(id);
// map the domain model to a view model (using AutoMapper):
var viewModel = Mapper.Map<DomainModel, ViewModel>(domainModel);
// pass the view model back to the view
return View(viewModel);
}

MVC Partial Views, Models and more

I am pretty new to ASP.NET MVC and I am trying to get my head around some of the design concepts at the moment. One thing I am currently stuck on is how (best) to handle a situation such as that described below.
Suppose I have a page that needs to render a number of "sections". For example, on the left hand side there is a list that is data driven and then the selected item in the list displays a further list in another section on the page. For better understanding lets suggest the left hand list is a list of movie categories and the other list displays a list of movies that are contained within that category, along with the various movie details.
Now, I have some form of ORM such as Entity Framework, LINQ to SQL or whatever that maps the tblCategory and tblMovie database tables into Category and Movie entities respectively. These entities live in the MyMVCApp.Data.Entities namespace. I then use a repository pattern located in the MyMVCApp.Data namespace to encapsulate the queries (via LINQ) against these entities to return our model entities.
This is where my first question lies. Should the repository be returning view model entities or domain entities which are then extended to produce view model entities? In my naive mind I see the entities returned from the ORM as simply containers for the data with domain entities containing the business logic. So surely there should be an abstration here?
Anyway, back to my scenario. Now lets assume I wish to present the two sections described at the beginning of this. I am assuming that what should be happening here is my domain entity model would contain a list of categories and their associated movies. So something like a List each of which contains a List.
This model would have been populated somewhere. This is my second question. Say my assumption above is correct and it is simply data entities are returned from the ORM. Now I have a namespace/project called MyMVCApp.Core.Model (or the like) with some domain entities such as the Movie and Category entities mentioned in the previous paragraph. Do these entities have methods on them to retrieve the data from the ORM and populate themselves? Or does the repository retrieve these populated entity models? And another question on this part, if I have a Movie and Customer entity in my ORM is it acceptable to be having domain entities named the same?
Finally, I assume the controller now has this populated list of Category and Movie objects and passes it back to the view. I am guessing it is best to have each of the sections described at the beginning as partial views and passing the populated model to each? So, it may be the IndexController which retrieves the populated CategoryMovies entity, passing this to the Categories partial view and the Movies partial view. I would then need to somehow determine the selected Category (quesrystring?) and display the appropriate list of Movies in that category within the view.
OK, so if anyone has got to this point in my ramblings I will take a deep bow. I hope I have explained my mixed up thoughts and questions in sufficient detail for someone to provide some kind of enlightenment.
Thanks for listening! :-)
Since you didn't mention it, I will assume you are new to DDD concepts. DDD compliments the "M" in MVC by placing logic where it belongs. And, I think a good amount could be applied here.
In strict DDD form, I would use your Movie example as an Aggregate Root (a DDD concept). Within Movie, you would have business logic (methods) that obtain the categories and related entities directly related to Movie (i.e. Categories-this-movie-belongs-in). This assumes the "category" list you want to display is a list of categories this movie is in.
public class Movie
{
private IList<Category> _categories;
public IList<Category> FetchCategories()
{
// you can lazy-load here, use Linq-to-Sql, etc.
return _categories;
}
public void AddCategory(Category c)
{
_categories.Add(c);
}
}
Of course, you can treat Categories as a Value Object (VO, a DDD concept) here if you don't have an identity on them.
Now, what gets more interesting is if you do want to keep an identity on your Categories, treating them as Aggregate Roots with multiple entities and relations to other VOs and alike. In this case, you would want to utilize the DDD concept of Services to combine the two aggregates into your requested Model you want to pass to your Controller. This allows you to create business rules around loading the categories.
public class Movie
{...}
public class Category
{...}
public class MovieCategory : Movie
{
private IList<Category> _categories;
public IList<Category> Categories
{
get
{
return _categories;
}
internal set
{
_categories = value;
}
}
}
public class MovieCategoryService
{
public MovieCategory FetchMovieCategoryByMovieId(int id)
{
MovieCategory mc = _movieRepository.FetchMovie(id);
// do some logic here, some checks, etc
// to obtain your Categories list. Maybe querystring?
IList<Category> cats = ...;
mc.Categories = cats;
return mc;
}
}
The concept is that you now have logic in the domain layer, in this MovieCategoryService, to handle the complex creation of these relationships, or using Factories to create complex types as well.
This gives you a model you can pass around to different View and PartialViews.
The final step in your original post is how to get this into the View. I've been playing with the ViewModel approach to this issue. Creating ViewModels either dynamically, or as a class, and hanging all of the entities on this ViewModel. A recent StackOverflow question hits on this concept. ViewModel Best Practices
I've passed the Model directly into Views, and I am now trying this approach. It does clean things up, as your DOmain Model really should be disconnected from the "logic" on your page. I find myself thinking, "Dang it. I need to get this partialview populated based on this ID. Guess that means another method on the entity." Going the ViewModel approach removes the logic/thinking from the Domain Model, and puts it where it belong - in the Application/UI layer of where you are fine-tuning your view/partialview.
First of all, I think you should just get started with a simple project and try the various scenarios out you pictured in your long question :). There is nothing written in stone, you can use whatever architecture with datalayers and services or whatever, you like !
Or does the repository retrieve these populated entity models?
I would say yes. Your controller graps these from the service and gets them, populated and all and just moves them to the view in order to be displayed.
I am guessing it is best to have each of the sections described at the beginning as partial views and passing the populated model to each?
And again i think you're on the right track ;).
It is a nice idea to give a view model entity to the view instead of the whole domain entity itself thereby providing the view only the required stuffs to work on
First of all return a List of Categories from your Domain, then construct a Movie view which takes the category name as a parameter something like this
- <Host>/Movies/Comedy
- <Host>/Movies/Horror
which would in turn display the movies which belongs to that particular category

Model design advice for ASP.NET MVC

I'm currently in the process of converting some small personal web sites from WebForms to MVC. With the existing sites, the database schema is solid but I had never really taken the time to build proper data/business models/layers. The aspx pages all talked to the database directly using a variety of Views and Stored Procedures that were created as needed for convenience. With MVC, I'm now trying to "do it right" as they say and use things like LINQ to SQL and/or the Entity Framework to build a proper data model or models for the application.
My question revolves around what goals I should have for building data models. I've read various pattern related articles and I realize that ultimately the answer is likely going to depend on the characteristics of my data. But generally should I attempt to build bigger models that encompass as much of the database as possible so that there's only one way to interact with a given set of tables? Or should I build smaller custom models for each MVC View that only contain the data and access that View will need?
Or should I build smaller custom models for each MVC View that only contain the data and access that View will need?
This would probably be better.
Do not forget, you can stick your models in hierarchies, so common properties, like ids, names, preferences can be present in each model.
Fat expanded models could be better for enterprise application, where framework automatically does lot of stuff based on preloaded user preferences, user roles, access rights etc. For a small personal project would probably be better to try to keep your models small and clean. It is also a protection. By not putting unnecessary data into a model you ensure your view will not by mistake display wrong entries or submitting a form would not by mistake overwrite some other data.
I would go for the model representing the actual data logic within your current system and have your controllers return the piece of the model which the view needs such as:
Controller:
public ActionResult index()
{
var ListOfObjects = DataHelper.GetAll();
ViewData.Add(ListOfObjects);
return View();
}
public ActionResult ViewObject(int id)
{
var Object= DataHelper.GetObject();
ViewData.Add(Object);
return View();
}
public ActionResult ViewObjectChild(int Objectid, int ChildId)
{
var Child= DataHelper.GetChildObject(Objectid, ChildId);
ViewData.Add(Child);
return View();
}
On the view
/
<% var myListOfObjects = ViewData.Get<IList<Object>>(); %>
/ViewObject/1/
<% var myobject= ViewData.Get<Object>(); %>
/ViewChild/1/1/
<% var myChild = ViewData.Get<Child>(); %>
Note I have used MVC Contrib typed functions I highly recommend these.
Generally, you would have one comprehensive domain model for the database. You can use (modify/add/remove/etc.) the domain model in your service layer or the controller if it is a small app.
However, for your views, you can use presentation objects to make the views easier to maintain. These are sometimes also called DTO or view model objects. Basically what you do is create an object that contains all the data from the model that is necessary for the view to be populated.
For example:
Your model may include:
public class Car()
{
public string Model;
}
public class Driver()
{
public string Name;
}
You want the view to output the name and model of the car and you would have to pass both the Car and Driver model objects the view.
Rather than sending the two model objects directly from the controller to the view, you can create an object which contains just the data you need:
public class CarAndDriverViewModel()
{
public string CarMake;
public string DriverName;
}
You would populate this object from the domain data and pass that to the view. And the view would be:
model.DriverName + ": " + model.CarMake
Now you don't have to worry about lazy loading issues or complicated view logic to deal with model peculiarities. It's more work to create these view model objects but they really help keep the view clean and provides an easy way to do formatting before sending data to the view.
There are projects and conventions you can use to help automate the creation of the view models, if you want to look into them. AutoMapper is an example.

Resources