ASP.NET MVC Entity Framework CodeFirst Many To Many (CRUD) - asp.net-mvc

I have a few problems but I'm going to start with the first and smallest. I have two models with a many-many relationship, Category and Project. In each model I have an ICollection of the other model. I initialize the collection as a new HashSet() for the Project constructor and vice-versa for the Category. I've read online that this will create a new table in your database with the PK of each model as the PK in the new table. I custom named them and whatnot through Fluent API but you get the idea.
This worked out great. So I make my Controllers and create and use scaffolding to create the CRUD views. I create a few categories.. Great. Now when I get to creating a a new Project, what I want is it to show me a list of the Categories I previously created, and to require at least one be selected before pushing through the Project. The view shows no categories to select at all and allows it to go through as null. I know how to make a property required but I don't know how to make a collection property required and grab all of the categories from the database to present in the Project create view for selecting....

Try :
Context.Project.Include(p=>p.Category)
inside your query code,
you will need
using System.Data.Entity;
to get the include method

For enabling lazy load, you will also need to mark your properties as "virtual"; otherwise, you will always have to eager load them using the .Include() method.

Related

ASP.NET MVC: Adding controller, what to set as model/data context?

I'm using MVC 4 and EF and I'm new to both. I've created an entity named TimesheetModel from an existing DB.
Question: When creating a controller (using the EF framework template) I have several options available to me under both "Model Class" and "Data Context class" dropdowns. By convention, would one usually create a controller per each model you needed to access? And the same for data-context? Also I'm not 100% sure on the data-context portion either.
I've gone through a few tutorials this morning on the topics but they seem to shy away from explaining the "why" you select what you select in those fields. Halp meh! Thx
In the Model Class, you select the class which you want EF to generate its Actions.
In the Data Context class, you type in the "Context" class in which all classes are declared. The context usually is the class which is the main where all starts exactly. If u used code first, you first create Context class, which shows which other classes are creating under it. Otherwise, if u do Database First, then the context is the name of the database usually.
Hope I could explain so you could understand.
The data context represents your database. Usually, in small application, there is only one.
The Model represents an entity, that almost always represents a table in database.
By convention, would one usually create a controller per each model
you needed to access?
It depends on the model. If you have a User class, you usually need to have a UsersController, to create, update and delete an user. If you have a UserRole class, you don't need an UserRoleController because it has a relation with User and you can use UsersController to handle UserRole too.
Keep in mind that there is no rule for that. You can do whatever you want. The Scaffolding of the MVC is just for teaching proposes.

How to get data from 2 entities in MVC ?

I am developing MVC application and using razor syntax. I have used model first method.
I have two entities, Customer and Lead. Lead is inherited from Customer.
When IsActive property is true then Customer treated as a Lead, otherwise it will be a customer.
Please check edmx file image.
Now, In regular entities we just deal with single entity and single table.
In this case how can I handle , Save and Load process. beacuse I have to store and load the record from 2 tables of DB.
Is Regular Index View will work here ?
When using inheritance in the Entity Framework you will have a single DbSet on your DbContext that exposes your hierarchy. In your database you have several options for configuring your table structure. For example you can use:
Table per Hierarchy
Table per Type
Table per Concrete type
(See this blog for a nice explanation: Inheritance in the Entity Framework.
In your queries however, you don't have to think about this. Your queries will have the following structure:
var leads = from l in dbcontext.Leads.OfType<Customer>()
select l;
The OfType() filters your collection to a subtype in your hierarchy. If you skip the OfType you will get both customers and leads in your resulting query.

Are there Visual Studio Tools For Creating DTO/ViewModel

I'm trying to introduce ASP.Net MVC to my department. I am encouraging them to have a ViewModel per View and AutoMapper for our larger projects (and ideally in general).
Sometimes this means having one large entity and picking 5 of its properties and creating the ViewModel. This is done by looking at the the edmx model (many projects were existing so it was DB first) and then creating matching properties in a ViewModel class. Obviously names etc have to match for AutoMapper to work. Also for navigation properties you have to add the navigation name first. Ideally also being able to type in a display name etc.
I'm trying to ease them into doing this (what they see as extra work). Is there any tool that would load a list of fields and allow you to select via checkbox etc and create the class from that?
I guess the same would apply to DTOs etc
Thanks
Have you tried this http://www.codesmithtools.com/product/generator
you can create a template of the dto and then it will generate the files/dto's for you as needed from any kind of datasource.

EF Code First - Entity joining multiple tables

I currently have an EF class that is backed by a database view (joining multiple tables). To make it updatable, I need to change the class to be backed by a database table. I am using Entity Framework 4.1 Code First and can't figure out how to set up those relationships?
To simplify, I currently have a Categories class that returns the Category Name (Categories table) and Category Type Name (CategoryTypes table). These are both in the database view that I currently use. I want to change to a ViewModel that brings back both of these fields directly from their tables and joins properly, that way when a user updates a Category Name, EF should be able to properly handle the update (since it will be updating the table instead of the view). Any tips on how to do this?
Table is a table - it is a single database object. If you want to remove your view and replace it with a table you need to delete your current tables (Categories and CategoryTypes) and create a single table which will contain denormalized data. That is pretty bad solution and it will cause you problems in the whole application.
Just to simplify description: It is not possible to replace your view constructed by joins among several tables with a table and it is not possible to make your view updatable.
You are doing it wrong because you are obviously mapping view models directly to your database. Map Catagories and CategoryTypes to entities load Category with its CategoryType and flatten them to your view model in your application logic (or load the view model through projection). Once user updates your view model decompose it back to separate entities and save them.

EF4 models and MVC models and view models ... To model or not model?

I'm currently working with EF4 and asp.net mvc 3 and I'm certainly having some trouble working through the different types of models that are possible when you bring these technologies together.
I have a database that I've defined and through EF4 I have a model of my database. But there is also the model that gets passed to my view and what about view models???
Lets say I have a mvc model of a project. This project has description, name and category properties. I have a view page that creates a project and returns it back to the controller for insertion into the database through ef4. So I initially created a class with those exact properties to be my model. However my page also requires a list of categories to choose from when creating that project, so I added a string array to my model which got passed to the page along with the other properties as part of my project model and it worked fine. Everything is great ... but I got to thinking ... because if the project model models a project then it shouldn't have a complete list of categories. It should only have the category that is part of that project.
But where does this complete list of categories go. In the view bag? This seems incorrect to me? Should I be creating a view model? How would this view model look? How about adding a method to the project model that would be something along the lines of GetCategories() then I could call this method from the view page ... but does that break the separation of concerns ideal in mvc?
I'm sure many people will have different views on the subject but any commentary that will help me wade through this mess will help.
Thanks,
In all the but simplest applications you're best off not passing Model objects to Views. A View should have a ViewModel which is constructed by a Controller using data from Model objects and which contains everything that View needs to display its information.
ViewModels decouple your presentation layer from your business layer, and your example demonstrates why this is important; your View needs information about a Project, but also a complete list of all Categories that Project could belong to - such a list does not logically fit into the Project domain model object, but fits perfectly logically into a ProjectViewModel.

Resources