Reputation: 1796
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?
Upvotes: 0
Views: 395
Reputation: 5489
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) {
...
}
Upvotes: 1
Reputation: 3847
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.
Upvotes: 1