Saroj
Saroj

Reputation: 526

Get data from multiple tables while editing in MVC

In MVC,I have designed a view where I am able to bind the datas from multiple tables i.e, I'm getting different records from 3 different tables which I am displaying in my Index.

Now on click of edit I want to send those datas to the edit view and this is where I am facing trouble.In my earlier forms,I was able to do this with db.find() which refers to only one table and based on its composite keys I was able to find all the datas corresponding to that table.

I want to get records from 3 tables on click of edit which I am successfully able to bind in my Index view.

Below is my Controller code:

objMyObj.MyModel = db.TableName.find(allcompositekeyshere);

According to me,I wont be able to get records from multiple tables with db.find as it will refer to only one table.So,For this I want some different logic. Any help would be appreciated.Thanks in advance..

Below is my linq query with which I am able to get all the records from city table along with country name from country table and state name from state table.

return objSvc.GetCityIndexData().Select(ct =>
                    new CityInputModel()
                    {
                        CityID = ct.CityID,
                        StateID = ct.StateID,
                        CountryID = ct.CountryID,
                        Name = ct.Name,
                        CountryName = ct.CountryName,
                        StateName = ct.StateName
                    }).ToList();

This is working fine for me to display the records in my index view. Now ,I want to display the same records in the corresponding textboxes at the time of edit.

Upvotes: 4

Views: 2468

Answers (1)

Yasser Shaikh
Yasser Shaikh

Reputation: 47774

You could try and use .Include() to include reference to your related tables.

var items = db.TableName
              .Include("FTable1")
              .Include("FTable2")
              .Where(allcompositekeyshere).ToList();

You cannot use Find directly - Find doesn't work with includes.

Here's what the EF team says

We have decided not to implement this because the syntax to call Find with an Include wouldn't be much simpler than the equivalent LINQ query:

ctx.Products.Include(p => p.Category).Single(p => p.Id == 3)

Find also has logic to retrieve the entity from memory if it is already loaded. This gets very complicated if we need to pull the entity from memory but then hit the database for some or all of the related entities (or vice versa).

Upvotes: 3

Related Questions