I'm working with asp.net mvc and Entity Framwork. I'm still getting familiar with this stack. I want to include data that has no foreign key relationship with the model being passed to the view.
Initially, the model was passed to the view like this...
public ActionResult Edit(int id = 0)
{
booking booking = db.bookings.Find(id);
return View(booking);
}
The data I need in the view does not have a FK relationship with booking.
I tried creating a seperate class to put both entities in...
public ActionResult Edit(int id = 0)
{
booking booking = db.bookings.Find(id);
viewModel.bookingtraces = (from l in db.traces where l.bookingid == booking.bookingid select l);
viewModel.bookings = booking;
return View(viewModel);
}
Currently, I'm getting an error with this though. The GET page will load, but when attempting to update, I get
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I also tried adding a modelBuilder entry to explicitly define the relationship, but that didn't work.
Ultimately, the question is, if there is no FK relationship between two entities, how do I access data in the view that isn't apart of the model being passed?
I would suggest rather than simply using Entity classes as your Model, you look into creating composite models, which contain the properties you require (I typically implement common functionality within a base view model, and inherit from that). This way you have full control of the instantiate of your model objects and what properties they include.
This way the entire model is posted back to the server when you POST back.
One advantage of the composite model, would be the ability to include many entities or POCO objects within a single model, for example:
public class MyModel {
public booking Booking {get;set;}
public SomeOtherEntityObject EObject{get;set;}
public SomePocoObject {get;set;}
}
These would then mean the entire contents of the model are posted back to the server.
You can can use your entity as model and pass additional data to the view by ViewBag
public ActionResult Edit(int id = 0) {
Booking booking = db.bookings.Find(id);
ViewBag.bookingtraces =
from l in db.traces
where l.bookingid == booking.bookingid
select l;
return View(booking);
}
OR
You can define a view model
public class MyViewModel {
public Booking booking { get; set; }
public IEnumerable<BookingTrace> traces { get; set; }
}
and then in your action method you can bind back only the booking property
[HttpPost]
public ActionResult Edit(Booking booking) {
...
}
Related
Extremely basic question about best practice in MVC when binding drop down lists.
This inst a real world example but a basic example that explains my question:
Take the following model
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Car Car { get; set; }
}
public class Car
{
public int ID {get;set;}
public string Make {get; set;{}
public string Model {get; set;}
}
Then assume that these get flattened into a view model:
public class IndexViewModel
{
public int PersonID;
public string Name;
public int SelectedCarID;
public SelectList<Cars> Cars;
}
In my constructor I have an index method:
[HttpGet]
public ActionResult Index()
{
var person = _ctx.People.FirstOrDefault(x=>x.ID == 1);
var vm = new IndexViewModel(){
Name = person.Name,
SelectedCarID = person.Car.ID,
};
return View(vm);
}
Now, Assume that the person that is returned from the context has NO car record when the page first loads.
The view has a line :
#Html.DropDownListFor(m=>m.SelectedCarID, Model.Cars)
When the form is submitted it is picked up by the action :
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
var person = _ctx.People.FirstOrDefault(x=>x.ID == model.PersonID);
var car = _ctx.Cars.FirstOrDefault(x=>x.ID == model.SelectedCarID);
person.Name = model.name;
person.Car = car;
_ctx.SaveChanges();
}
Now that is the way I have done it for ages, I started using EF back when LINQ to SQL was taking off and I have always created my models like that as I was under the imperssion that it was the recommended way.
After a discussion with another developer today I am not sure if this is stil the best way? It has always irked me that I need to do a lookup against the database to get the Car record out just so that I can update the record.
My questions are:
What is the best way to achive what I have described above?
Is the above correct?
Is there a better way to update the car entity against the person without doing a lookup (Preferably without including the foreign keys in the model)?
Is it better to just include the FKs in the model (Its not the way Ive been doing it bit it seems more sensible)?
Is there a way to bind the drop down to the car object (The guy I spoke to seemed to suggest you could but my knowlege of MVC/asp.net and furious googling seems to indicate that you cant)?
This really ins't the place for Best Practices sort of questions (that would probably be Code Review).
However some notes initially.
Keep your domain objects in the domain
The first thing that stood out to me was the SelectList<Car> property. Where it appears as your Car entity is actually a domain entity. A domain entity should not be exposed to the UI for multiple reasons.
Entity framework proxy classes monitor changes to properties that can be inadvertently saved.
Re-factoring of domain entities requires re-factoring of UI Code.
Domain entities typically contact properties you would not like exposed or otherwise.
Serialization of the Domain Entities will also serialize navigation properties and (mostly likely) cause circular reference errors.
Your question
Given the above you know have your answer, you will have to do a lookup for an entity based on your criteria from your View Model. Your view model should not have any understanding of the data context. It is in fact a View Model not a Domain Entity. By telling your View Model to interact with your data contexts you have no separation between your Data Access layers and your Presentation layers.
Don't make your controller manage data access as well
Your controller has a lot of work to-do, managing data access shouldn't be one of them. Doing so you have infarct coupled your Presentation Layer with your Data Access layer. Now as this is an example its easy to forgive however re factoring your data access layer will have direct consequences to your Presentation layer. I would suggest places a Services layer in between your data access layer and the presentation layer.
Ok All this in practice how does it look.
This is my personal approach here but will look at decoupling the data layer from the Presentation layer, no domain objects passed to the Presentation layer and using services to broker the transactions to the data layer.
Sample Service
This service is responsible for handling the interaction between the data layer and presentation (note mock repositories).
public class SampleService
{
public SampleService()
{
_dbContext = new SampleContext();
}
readonly SampleContext _dbContext;
public virtual Person GetPersonById(int id)
{
return _dbContext.Persons.FirstOrDefault(x => x.ID == id);
}
public virtual Car GetCarById(int id)
{
return _dbContext.Cars.FirstOrDefault(x => x.ID == id);
}
public virtual IList<Car> GetAllCars()
{
return _dbContext.Cars.ToList();
}
public virtual void UpdatePerson(Person person)
{
if (person == null)
throw new ArgumentNullException(nameof(person));
_dbContext.SaveChanges();
}
public virtual void UpdateCar(Car car)
{
if (car == null)
throw new ArgumentNullException(nameof(car));
_dbContext.SaveChanges();
}
}
Does this appear to be more work, absolutely does but better to implement your service now than have to do it later. What we also achieve is one location to update if we wish to change any queries or interaction methods.
IndexViewModel
As we have agreed we are no longer passing the car object to the SelectList. Infact we only need to construct a basic IList<SelectListItem> and populate this from our controller.
public class IndexViewModel
{
public IndexViewModel()
{
AvailableCars = new List<SelectListItem>();
}
public int PersonID { get; set; }
public string Name { get; set; }
public int SelectedCarId { get; set; }
public IList<SelectListItem> AvailableCars { get; set; }
}
Controller
Now our controller is pretty simple to wire up.
[HttpGet]
public ActionResult Index()
{
var person = sampleService.GetPersonById(1);
var model = new IndexViewModel
{
Name = person.Name,
PersonID = person.ID,
SelectedCarId = person.Car.ID
};
model.AvailableCars = sampleService.GetAllCars()
.Select(car => new SelectListItem
{
Text = $"{car.Make} - {car.Model}",
Value = car.ID.ToString()
})
.OrderBy(sli => sli.Text)
.ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
var person = sampleService.GetPersonById(model.PersonID);
if(person != null)
{
person.Name = model.Name;
//only update the person car if required.
if(person.Car == null || person.Car.ID != model.SelectedCarId)
{
var car = sampleService.GetCarById(model.SelectedCarId);
if (car != null)
person.Car = car;
}
sampleService.UpdatePerson(person);
}
return View();
}
View Drop Down list
#Html.DropDownListFor(m => m.SelectedCarId, Model.AvailableCars)
If you compare your code to my code I have actually added more code to the solution, however removes a lot of coupling and dependencies that could become hard to manage in larger applications.
Now back to your original questions.
Is there a better way to update the car entity against the person without doing a lookup (Preferably without including the foreign keys
in the model)?
No, you should be doing a lookup for that entity (car) outside of the Model. The model should not be aware of the data context.
Is it better to just include the FKs in the model (Its not the way Ive been doing it bit it seems more sensible)?
NO, your model should not be aware of the data context, therefore you do not need to define foreign keys (in a data context sense) leave that to your controller and services.
Is there a way to bind the drop down to the car object (The guy I spoke to seemed to suggest you could but my knowlege of MVC/asp.net
and furious googling seems to indicate that you cant)?
You could, but you don't want to. Our Car entity is a domain entity and we dont want to expose the entity to the UI (Presentation). Instead we will use other classes to expose what properties are bound. In this example a simple IList<SelectListItem> was more than sufficient.
I got one question related to my model you can see in the picture below.
As you can see I got 3 entities and 1:n and m:n relations between them.
I want that I can edit these models through a web interface. Therefore I scaffold (add controller with entity framework) these three models and got edit/delete/create/ views and of course one controller for each entity.
But there is no input/fields created for the relations automatically by VS. So I thought to implement them manually. Before I want to do that is there an simpler way to implement/scaffold this model, so I can even edit the relations(Checkboxes or (multi)select would be the best)?
Thanks in advance!
For one-many you can use a DropDownList for Tip in the Partner View (see Scott Allen's solution. Many-many can be handled by ViewModels and JavaScript frameworks like Knockout.
No, the scaffolds are intentionally unopinionated here, as there's many different ways you could handle this. Perhaps you just want to choose from a select list? Maybe you want checkboxes, instead? Or, maybe you want to actually add/edit related items inline? And with that last one, would you like to post all at once or use AJAX?
So, instead of picking for you, the framework rightly leaves the decision up to you, since only you know how your application should be built. Regardless, relying on the scaffolds is going to bite you more often than not. They only work in the most basic and ideal scenarios, and when have application requirements ever been either basic or ideal? I don't even bother with them at this point, preferring to just create my controllers/views manually. It ends up being quicker than dealing with the scaffold and undoing all the things that aren't applicable.
So, since you're looking for select boxes (either single-select or multi-select), first, I'd recommend creating view models for your entities. For example, with Tip:
public class TipViewModel
{
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
public int? SelectedPartnerId { get; set; }
public IEnumerable<SelectListItem> PartnerChoices { get; set;}
[Required]
public int? SelectedBookId { get; set; }
public IEnumerable<SelectListItem> BookChoices { get; set; }
}
Here, I've added nullable int (using a nullable allows them to be initially unselected, instead of just set to the first option) properties to track the id of the selected Book/Partner because it doesn't appear you have explicit properties on your entities for the foreign keys. That's fine, but it doesn't make it slightly more complicated to save the relationship, as you'll see in a bit. If you did have explicit foreign key properties, then you should mirror those in your view models instead.
Now in the GET version of your action, you'll need to do something like the following:
public ActionResult Create()
{
var model = new TipViewModel();
PopulateChoices(model);
return View(model);
}
...
protected void PopulateChoices(TipViewModel model)
{
model.PartnerChoices = db.Partners.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = m.Name
});
model.BookChoices = db.Books.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = string.Format("{0} by {1}", m.Name, m.Author)
});
}
I've abstracted out the code for populating these select lists because the code will be used multiple times throughout your controller. Also, I used string.Format on the Text value for the books just to show that you can do whatever you want with the text for the select list item. Also, the code above would be for a create action, obviously. Doing an edit would be similar but slightly different:
public ActionResult Edit(int id)
{
var tip = db.Tips.Find(id);
if (tip == null)
{
return new HttpNotFoundResult();
}
var model = new TipViewModel
{
Name = tip.Name,
Description = tip.Description,
SelectedPartnerId = tip.Partner != null ? tip.Partner.Id : new int?(),
SelectedBookId = tip.Book != null ? tip.Book.Id : new int?()
}
PopulateChoices(model);
return View(model);
}
The main difference is that you're obviously dealing with an existing instance so you need to pull it from the database. Then, you just need to map the data from your entity onto your view model. Since, again, you don't have explicit foreign key properties, you have to do a little extra leg work to get the currently chosen Partner/Book values, otherwise you could just copy the values for the foreign key properties over directly. Also, here, I'm just doing a manual mapping, but there's third-party libraries to make this task easier (see: AutoMapper).
With that, you can implement your views. Everything will work the same as it did when you were using the entity directly, you just need to make a couple of modifications. First, you'll need to change your view's model declaration:
#model Namespace.To.TipViewModel
Then, add the select lists for your two related properties:
#Html.DropDownListFor(m => m.SelectedPartnerId, Model.PartnerChoices)
...
#Html.DropDownListFor(m => m.SelectedBookId, Model.BookChoices)
The fun happens in the POST version of your actions. Most of the code will stay the same from the GET version, but now you'll have an if (ModelState.IsValid) block:
[HttpPost]
public ActionResult Create(TipViewModel model)
{
if (ModelState.IsValid)
{
// map the data from model to your entity
var tip = new Tip
{
Name = model.Name,
Description = model.Description,
Partner = db.Partners.Find(model.SelectedPartnerId),
Book = db.Books.Find(model.SelectedBookId)
}
db.Tips.Add(tip);
db.SaveChanges();
return RedirectToAction("Index");
}
// Form has errors, repopulate choices and redisplay form
PopulateChoices(model);
return View(model);
}
The edit version, again, is similar, except you're going to map onto you existing instance, for example:
tip.Name = model.Name;
tip.Description = model.Description;
tip.Partner = db.Partners.Find(model.SelectedPartnerId);
tip.Book = db.Books.Find(model.SelectedBookId);
That's all there is to it for reference properties. You don't actually have any thing that's M2M or even one-to-many on your entities in your question. Everything is one-to-one, but if you did have a collection property, you'd need to handle it slightly differently. You still need a property on your view model to hold the selected values and the available choices:
public List<int> SelectedFooIds { get; set; }
public IEnumerable<SelectListItem> FooChoices { get; set; }
Populating the choices would also be the same. The options are the options; it doesn't matter if you're select just one or many as far as that is concerned.
Mapping onto your entity in your create action would be different though, as you'd need to select all of the chosen items from the database and set your collection property on your entity to that:
var tip = new Tip
{
...
Foos = db.Foos.Where(m => model.SelectedFooIds.Contains(m.Id)),
}
And, you'd need to make changes to both the GET and POST versions of your edit action. For the GET, you need to condense your collection property down to a list of ids:
var model = new TipViewModel
{
...
SelectedFooIds = tip.Foos.Select(m => m.Id).ToList(),
}
And in the edit version, you set new selected items:
tip.Foos = db.Foos.Where(m => model.SelectedFooIds.Contains(m.Id);
Finally, in your views, you'd use ListBoxFor instead of DropDownListFor to enable the multiselect:
#Html.ListBoxFor(m => m.SelectedFooIds, Model.FooChoices)
I'm having trouble grasping the proper way to create view models and save that info back to the database using Entity Framework, and I can't seem to find the info I'm looking for, so please forgive me if I have overlooked it.
I came across this post here and he seems to be asking the same question but doesn't get an answer.
My main questions are,
For editing purposes, If I have a ProductModel model that has a Warranty model relationship, should I be using virtual property Warranty in the view model or should I be using int WarrantyId?
If I should be using a virtual property, why doesn't this code save the Warranty properly?
Do I need to explicitly flag or populate the Warranty for update?
Please not this does populate my edit view and select lists as intended.
My (simplified) code is setup as follows:
Model:
public int ModelId{ get; set; }
public int ModelNumber { get; set; }
public virtual Warranty Warranty { get; set;}
View Model:
public int ModelId { get; set; }
[Required(ErrorMessage = "Model Number required")]
[StringLength(25, ErrorMessage = "Must be under 25 characters")]
[Display(Name="Model Number")]
public string ModelNumber { get; set; }
//related objects and necesary properties
public virtual Warranty Warranty { get; set; }
public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }
Controller (GET):
public ActionResult Edit(int? id)
{
//check the id
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//get the model and make sure the object is populated
var model = _modelService.GetModel(id.Value);
if (model == null)
{
return HttpNotFound();
}
//pass our entity (db) model to our view model
var editModelModel = new EditModelModel();
editModelModel.InjectFrom(model);
//warranty select list
editModelModel.WarrantySelectListItems = WarrantySelectList(editModelModel.Warranty.WarrantyId);
//option multi select list
editModelModel.OptionSelectListItems = OptionSelectList();
return View(editModelModel);
}
Controller (POST) (work in progress):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditModelModel editModelModel)
{
if (!ModelState.IsValid)
{
return View(editModelModel);
}
var modelEntity = new Model();
modelEntity.InjectFrom(editModelModel);
_modelService.Update(modelEntity);
_unitOfWork.Save();
return RedirectToAction("Index");
}
View (simplified):
<div class="form-group">
#Html.Label("Warranty", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.Warranty.WarrantyId, Model.WarrantySelectListItems, "--Select--")
#Html.ValidationMessageFor(model => model.Warranty.WarrantyId)
</div>
</div>
Again, I just want to know the proper/best way to set up these viewmodels and models so the EF is doing as much of the work as possible. I feel like if I have to create a WarrantyId field, I'm doing something wrong, but maybe that isn't the case.
Thanks in advance. Any insight/help is greatly appreciated.
For editing purposes, If I have a ProductModel model that has a
Warranty model relationship, should I be using virtual property
Warranty in the view model or should I be using int WarrantyId?
You don't use virtual keyword for the property of your ViewModel, because the ViewModel has nothing to do with Entity Framework.
The reason to use the virtual keyword is to allow lazy loading in Entity Framework. In your case, if you add the virtual keyword for
the Warranty navigation property in the Product POCO class, you can access the Warranty property like below:
Model.Warranty.WarrantyId
And the reason it didn't save the Warranty information into your Database is because you need to define a Warranty foreign key property in the Product class.
In your case, if you're using code first approach and Product is your POCO class, just keep it simply like below:
public class Product
{
public int ModelId { get; set; }
public int ModelNumber { get; set; }
public int WarrantyId {get;set;}
[ForeignKey("WarrantyId ")]
public virtual Warranty Warranty { get; set; }
}
Then your ViewModel :
public class MyViewModel
{
public Product Product { get; set; }
public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }
}
Finally your view
#model MyViewModel
#Html.DropDownList("Product.Warranty.WarrantyId", Model.WarrantySelectListItems, "--Select--")
#Html.ValidationMessageFor("Product.Warranty.WarrantyId")
Of course, you need to change your action methods to meet the ViewModel.
For editing purposes, If I have a ProductModel model that has a Warranty model relationship, should I be using virtual property Warranty in the view model or should I be using int WarrantyId?
You shouldn't be using virtual properties in your view models. A view model simply represents the slice of data that is necessary to display a view. As you are mapping to that view model from your entities, you don't need to mark anything as virtual. See this answer, if you want to know what virtual is doing with regards to the Entity Framework.
Also, you should only be including the information necessary to render that view. So if you just need the WarrantyId in the view, then only include that.
As you're also model-binding back to the same view model in your POST action, you should be very specific about what you want your view model to represent, otherwise you leave yourself open to an over-posting attack.
I feel like if I have to create a WarrantyId field, I'm doing something wrong, but maybe that isn't the case.
It isn't the case. Each of your views should be self-contained. When you first starting using view models, one-per-view, your initial reaction is that of violating DRY. However, each view has different requirements. In terms of view models themselves, the most obvious distinction is validation. If you use entities in your views, all of those views are tied to the validation rules you've applied to your entities. (You'd also be vulnerable to over-posting if you don't want the user to be able to edit the entire entity.)
However, by having separate view models for your views, and applying the validation rules on the view models themselves, you can now have different validation requirements in your views. For example:
public class ViewAViewModel
{
[Required]
public int WarrantyId { get; set; }
}
public class ViewBViewModel
{
// No longer required.
public int WarrantyId { get; set; }
}
If you'd have included Warranty directly in both of these views, you'd have been stuck with one set of validation rules.
That aside, I'm wondering why you have this on your model (which I assume is an entity):
public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }
That doesn't belong here. This is a presentation detail, and it should not exist in your business objects. It should exist on your view model.
What you're dealing with are definitely navigation properties (the virtual properties on your model classes), and this does a good job of explaining them:
http://msdn.microsoft.com/en-us/data/jj713564.aspx
The tricky parts in defining these are really in how you set up your DbContext for the database. The official doc on this is here:
http://msdn.microsoft.com/en-us/data/jj591620
Simple parent-child relationships are pretty easy to handle, and there are additional situations (trickier) where you can define a number of models that physically come from the same row in a table, but I don't think you're dealing with that here.
The MVC part is a separate concern, and ideally you should treat it as such. Controller code should only delegate real "work" to other classes. The unit of work pattern, if you choose to use it, isn't really necessary until you get into situations where you've got a big lump of stuff to persist/edit across many tables or entity sets, with the idea that you may want it all to fail or succeed as a whole. If you're just handling simple persistence of single objects, don't even complicate it with the unit of work pattern.
The other thing to keep in mind with EF, or any ORM framework, is that it needs to track changes or compare to existing records, so the key values become super important as you work through this.
A ViewModel is a simplified view of your data that is UI aware and includes only information you need for UI rendering and User Input.
It might seem wrong to do more work - why not use the model directly? But with complex systems you end up with a lot of complexity and often you need to change the Model to accomodate the UI and it's a mess.
Also, ViewModels allow you to test the UI without having a database present and without that complexity. You really decouple UI issues and Data Modeling issues.
I usually end up NEVER using Models on the UI at all, always through ViewModel that simplifies my life in the end even if it's more work first.
So let's do a couple of changes.
View Model (Renamed to EditViewModel for clarity):
public int ModelId { get; set; }
// Removed for clarity, include needed properties in the UI
public int WarrantyId { get; set; }
public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }
Controller (GET):
public ActionResult Edit(int? id)
{
//check the id
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//get the model and make sure the object is populated
var model = _modelService.GetModel(id.Value);
if (model == null)
{
return HttpNotFound();
}
//pass our entity (db) model to our view model
var editViewModel = new EditViewModel();
editViewModel.InjectFrom(model);
// You could instead create a custom injection like FlatLoopValueInjection
// That would flatten and remove duplicates from
// Model.Warranty.WarrantyId to ViewModel.WarrantyId
editViewModel.WarrantyId = model.Warranty.Id;
//warranty select list
editViewModel.WarrantySelectListItems = WarrantySelectList(editViewModel.WarrantyId);
return View(editViewModel);
}
Custom Injection Flatten - FlatLoopValueInjection:
http://valueinjecter.codeplex.com/wikipage?title=flattening&referringTitle=Home
Controller (POST):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditViewModel editViewModel)
{
if (!ModelState.IsValid)
{
return View(editViewModel);
}
// You need to reconstruct the model itself, there are faster ways but I wanted
// to showcase the logic behind it
// I didn't do any null check or anything to simplify
// Load the model used from the database
var modelEntity = _modelService.GetModel(editViewModel.ModelId);
// You can do an InjectFrom for the other properties you need
// with custom Injection to unflatten
modelEntity.InjectFrom(editViewModel);
// Load the selected warranty from the database
var warrantyEntity = _warrantyService.GetWarranty(editViewModel.WarrantyId);
// Update the warranty of the model with the one loaded
modelEntity.Warranty = warrantyEntity;
_modelService.Update(modelEntity);
_unitOfWork.Save();
return RedirectToAction("Index");
}
Now in your view:
<div class="form-group">
#Html.Label("Warranty", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.WarrantyId, Model.WarrantySelectListItems, "--Select--")
#Html.ValidationMessageFor(model => model.WarrantyId)
</div>
</div>
As a side note, in your models and view models, you should try to never repeat prefixes in names like:
Model.ModelId
Warranty.WarrantyId
Unless it's a foreign key or value:
Model.WarrantyId
Why? It's a LOT easier to flatten/unflatten them by convention with InjectFrom:
Model.Warranty.Id => (flatten) => Model.WarrantyId => (unflatten) => Model.Warranty.Id
Also, it's a best practice. The name of the model/table already tells you the entity type, no need to repeat it.
You have to have int WarrantyId in your view model.
Than in your view
#Html.DropDownListFor(x => x.WarrantyId, Model.WarrantySelectListItems, "--Select--")
In Controller (POST) take WarrantyId (selected from dropdown) and find object from database (var warranty = db.Warranties.Where(w=>w.WarrantyId == editModelModel.WarrantyId or something like that) and that object assign to modelEntity.
I have my view model :
namespace projInterview.Models
{
public class QuestionViewModel
{
public piQuestion Question { get; set; }
public List<piAnswer> Answers { get; set; }
public piQuestionFavorite QuestionFavorite { get; set; }
public piQuestionLevel QuestionLevel { get; set; }
public QuestionViewModel(piQuestion question, List<piAnswer> answers )
{
Question = question;
Answers = answers;
}
}
}
The VM is a standalone class. I did not scaffold this out to a controller.
In my controller:
namespace projInterview.Controllers {
public class QuestionController : Controller
{
private ProjectContext db = new ProjectContext();
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
piQuestion piquestion = db.piQuestions.Single(x => x.QuestionID == id);
List<piAnswer> piAnswers = db.piAnswers.Where((x => x.QuestionID == id)).ToList();
var questionViewModel = new QuestionViewModel(piquestion,piAnswers);
return View(questionViewModel);
}
}
When I get to this line:
piQuestion piquestion = db.piQuestions.Single(x => x.QuestionID == id);
I get the following error:
One or more validation errors were detected during model generation:
projInterview.DAL.QuestionViewModel: : EntityType 'QuestionViewModel'
has no key defined. Define the key for this EntityType.
questionViewModels: EntityType: EntitySet 'questionViewModels' is
based on type 'QuestionViewModel' that has no keys defined.
piQuestion and piAnswer both have keys in the original models that the viewmodel is using. What am I doing incorrectly?
Wait wait wait. A view model has absolutely nothing to do with an Entity framework context. It should not be associated with it. What you seem to have right now is that db.piQuestions is an IQueryable<QuestionViewModel> which is an absolutely wrong thing to do. A view model doesn't know anything about EF and EF doesn't know anything about view models.
NEVER map your view models to any database or EF stuff. What you put as IQueryable<T> properties to your DBContext are your Domain Models. Those are the models that are bound to your database tables.
Then in your controller action you make one or more calls to your database (DbContext) in order to retrieve one or more of those domain models. Then you map (copy the properties) of those domain models to a single view model. Finally you pass the view model to the view.
Also as a side remark, view models usually have default constructors. You don't need those specific constructors taking parameters. That will just make the default model binder insane if you attempt to have such view model as parameter to a controller action.
So to conclude: view models do not have any keys. They should not even know what a key is. A key is something specific to your Data Access Layer that is to say to your Domain Models.
For the sake of completion: when selecting a model in the View scaffolder, a domain model is expected, so it also pre-populates the Data context class and as such it expects a key. When selecting a viewmodel, simply delete the pre-filled DAL class and leave the DAL field blank.
If you actually define a key for a viewmodel, as I wrongly did, the scaffolder adds a definition of the viewmodel to the context class. To remedy the mess I had made, I deleted the viewmodel definitions from my context class and removed the keys from my viewmodels.
I finally got the idea from this answer.
I want to understand (and finally appreciate because now it's only pain...) more ViewModels and strongly-typed Views in MVC.
My ViewModel
public class Combined
{
public IEnumerable<Domain> Domains { get; set; }
public IEnumerable<RegInfo> RegInfos { get; set; }
public Combined(IEnumerable<Domain> domains, IEnumerable<RegInfo> reginfos)
{
this.Domains = domains;
this.RegInfos = reginfos;
}
In Controller I pass data from repositories to an object of type Combined.
public ActionResult RegDetails(int id = 0)
{
var domain = from x in unitofwork.DomainRepository.Get(n => n.ID == id)
select x;
var reginfo = from y in unitofwork.ReginfoRepository.Get(n => n.ID == id)
select y;
var regdetails = new Combined(domain, reginfo);
return View(regdetails);
}
In a View (using Razor) I have #model project.namespace.Combined so I'm passing an object that holds two lists.
1/ Why can't I access each list item like this #Model.Domain.Name (noobish question but please help me to understand logic behind it)? I can do it form View "level" by using join but it's totally against MVC pattern. I think that only place to join those two tables is in Controller but it will create totally new object so do I need to create a Model for it?
2/ What's the best approach to get an IEnumerable object that will hold data from 2 or more tables that can be used to populate View (join, automapper)?
3/ Is there an approach that will allow me to create a Model that I will be able to use to POST to multiple tables from one FORM?
Thanks in advance.
The logic of fetching the entities in your controller action is fine; that's the job of the controller. You don't, however, need a custom constructor on your view model: just use object initialization.
var regdetails = new Combined { Domains = domain, RegInfos = reginfo }
Now, as far as your view model goes, Domains and RegInfos are IEnumerables, but you're only fetching a single object for each. If your intention is to have a list type, then you should modify your LINQ to select multiple items, but if your intention is to in fact have just one object for each, then you should not use IEnumerables in your view model.
public class Combined
{
public Domain Domain { get; set; }
public RegInfo RegInfo { get; set; }
}
If you do that, then you will be able to access the Name property on the Domain instance with just #Model.Domain.Name. However, if you keep them list-types, then you must loop through them in your view (even if there's only one item in the list):
#foreach (var domain in Model.Domains)
{
// Do something with domain.Name
}
You get indeed a Model property in your view, and you can use Domains and RegInfos properties like you would do in c#. For example :
#{
var firstDomain = Model.Domains.FirstOrDefault();
// do some process with this variable
}
Or :
#foreach(var regInfo in Model.RegInfos)
{
// do some other process
}
If displayed data come from various data sources, it is best to make a specific view model. You need to avoid making calculations or applying business rules in your view, data should be preformatted before that. Another benefit is to pass only required data to your view : you don't want to fetch a huge object (or collection) from your database just for 2 displayed properties.
That view model can also be used when you submit a form. You can get it back if your post action has a parameter of the view model type, and if you correctly generate inputs in your view (by using some HtmlHelper like Html.Editor(For), etc).
Anyway, there's a lot to say about strongly typed views, and many resources / tutorials can be found across the web.