I’m creating an expense report project – my first using MVC.
This is a Database First project and I’m using Oracle ODP.
I have an entity model with the following classes:
ExpenseReport
ExpenseItem
ExpenseType
The expense report will have many expense items.
Each expense item will be of a specific expense type from the list of types in that ExpenseType class – thus a many-to-one relationship.
A single expense type record contains for each type a category, and headings for description/comment field to go with that type.
In my view, I am able to display the report with a list of all the expense items for that report. I am doing this through my Edit or Details controllers with the following code:
public ActionResult Details(long id)
{
using (var db = new Entities())
{
var thisReport = db.ExpenseReport.Find(id);
thisReport.expItems = db.ExpenseItem.Where(e => e.BB_EXPREPORT_ID == id).ToList();
return View(thisReport);
}
}
I tried adding this to the code (just above the return View line) to also include the expense type values (category, headings) for each type but it is failing due to a casting issue – cannot implicitly convert (are you missing a cast?)
foreach (ExpenseItem item in thisReport.expItems)
{
item.expType = db.ExpenseType.Where(e => e.BB_EXP_TYPE == item.BB_EXP_TYPE);
}
My questions:
- Isn’t there a way I can set up my model classes so that I don’t need
to add these statements? I.E. Can’t I modify the virtual object Get
statement to pull them there? Or can I modify the entitymodel file
to get these values? Is it a loading issue? I turned off lazy
loading. - If there is not a way to do this at the model level so that virtual
objects are included in the get, then how can I set the cast in my
code above to pull the values from the ExpenseType table for that
given expense type?
Thanks.
Admittedly, I’m not sure of what you’re trying to do, but it looks like you just want to load up your object all at once. You can do this with Entity Framework using the Include method.
I’d assume you’re using the “pluralization” feature for naming your db sets, but then again, your call to “db.ExpenseReport” is missing an (s) at the end.
Then you can use it in your Razor view like so.