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.
Related
I have my entity as:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
I have my UserViewModel as
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
I am using these as below in my controller:
//This is called from my view via ajax
public void Save(UserViewModel uv)
{
// this throws error: cannot convert from UserViewModel to Entity.User
MyRepository.UpdateUser(uv);
}
My UpdateUser in repository class is as below:
public void UpdateUser(User u)
{
var user = GetUserDetails(u.Id);
user.Name = u.Name;
user.Address = u.Address;
//using entity framework to save
_context.SaveChanges();
}
How can I correctly map UserViewModel in my controller to my entity
By using AutoMapper you can do something like:
public void Save(UserViewModel uv)
{
// this throws error: cannot convert from UserViewModel to Entity.User
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<UserViewModel , User>();
});
User u = config.CreateMapper().Map<User>(uv);
MyRepository.UpdateUser(u);
}
Or manually :
public void Save(UserViewModel uv)
{
User u = new User()
{
Id = uv.Id
Name = uv.Name;
Address = uv.Address;
};
MyRepository.UpdateUser(u);
}
Which is not good to do it manually if you change your view-model and your model then you should change your code also, but with Automapper you don't need to change the code.
EDIT1:
This is not good idea to use model-view in repository (DataAccess Core) so it would be better to keep your public void UpdateUser(User u) and don't change it, in outside it is better to pass user to UpdateUser not UserViewModel like what you have done before.
EDIT2:
In my opinion non of answered posts doesn't related to SOC (Separation on concerns) even mine...
1- When I passed UserViewModel I've violated the SOC ....
2- In the other side if I got User in Peresentation layer directly I also violated the SOC.
I think the best way is a middle layer as proxy....
Presentation <----> Proxy <----> Repository.
Your repository deals with objects of type User, so you need to map the values back to an instance of that type and then make the call.
Assuming you have a method to get the user called GetUser:
public void Save(UserViewModel uv)
{
var user = MyRepository.GetUser(uv.Id);
user.Name = uv.Name;
user.Address = uv.Address;
MyRepository.UpdateUser(user);
}
You can then save the changes in your repository class. You can attach the object to make sure there are no issues if the object was created in a different context:
public void UpdateUser(User u)
{
_context.Users.Attach(u);
_context.Entry(u).State = EntityState.Modified;
_context.SaveChanges();
}
You are doing the mapping of property values(view model->enity model) inside your repositories UpdateUser method. So use the view model class (UserViewModel) as the parameter type of that.
public void UpdateUser(UserViewModel u)
{
// Get the entity first
var user = GetUserDetails(u.Id);
// Read the property values of view model object and assign to entity object
user.Name = u.Name;
user.Address = u.Address;
//using entity framework to save
_context.SaveChanges();
}
Now from your Save method ,you can pass the view model object to this method.
This will fix your compile time error (which is your current problem in the question), but be careful about what classes you are using in what layers. If you are too much worried about using a view model class in your data access layer, you can do that in a middle service layer. But then you are getting the entity model in that layer and doing the update there.
Remember, there is no definite answer for that question. Use the approach you think is readable and consistent with the project/ team. Often times, i tend to use the term "Common DTO classes" than "View models" so i can peacefully pass those around to another layer. I keep them in a separate project (called Common DTO) and this will be cross cutting across other projects. That means i will add a reference to this Common DTO project in my Web/UI layer and my data access/service layer and use those as needed.
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 am new to asp.net MVC and i have created a project using Entity Framework code first approach. I have put my POCO objects in to a separate class library called Entities.
Now i would like to get some data from my service class, which returns an Entity and output that to the View. here is some very basic code
// in POCO library
public class MyEntity() {
public int Id { get; set; }
public String Name { get; set; }
}
// in service library
public class EntityService() {
public MyEntity Get(int id) {
return new MyEntity() { Id=1, Name="This is my entity name" };
}
}
// controller in asp.net MVC web application
public MyController() : Controller
{
private EntityService _service;
public MyController(EntityService service) {
_service = service;
}
public ActionResult Index()
{
MyEntity entity = _service.Get(1);
return View(entity);
}
}
Now should i push MyEntity to the View, or should i be creating a separate ViewModel? Part of me thinks that creating a separate ViewModel would be best as to keep the separation between the Entities and my View, and also the "logic" to copy the fields i need would be in the controller. But another part of me thinks that creating a ViewModel is just going to be a near copy of the Entities so seems like a waste of time?
I would like to do it correctly, so thought i would ask here. Thanks in advance
Viewmodel is best solution.
You can put attributes(validations and other)
Your viewmodel can contain data from several data entities
As you say you get separation between the Entities and View
General approach get entities in controller and use some mapper library(I recommend emit mapper)
to map entity to your viewmodel
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'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) {
...
}