How to fetch data with EF on one to many relationship.
ie if i have a table name Person(personID as primary key) and another table name streetLivedIn(personID as foreign key). Now i force my controller method to pass an object of type person
var persons=db.persons();
return View(persons);
Now i want to display Person details along with street(ie that what stored at streetLivedInTable) he/she lived at.
suppose i have an Entityset of person
public class Persons
{
public string Name{get;set;}
//NAVIGATIONL PROP.
public virtual ICollection<streetLivedIn>{get;set}
}
Suppose the navigational property name is Streets
.
public class Persons
{
public string Name { get; set; }
//NAVIGATIONL PROP.
public virtual ICollection<streetLivedIn> Streets { get; set }
}
Then you can use the Include
method to eager load this property.
var persons = db.persons.Include("Streets");
return View(persons);
You can display this in various ways. Eg
@foreach (var person in Model)
{
<div>@person.Name</div>
@foreach (var street in person.Streets)
{
<div>@street.Name</div>
}
}
Or you can use the WebGrid
, MvcContrib Grid
, etc
Assuming you don't want to expose the Entity Framework data model directly to the view, and instead do a conversion to business objects you create, I would simply iterate the EF datamodel with a double foreach loop. Entity Framework creates the one-to-many-references for you using containment - why not take advantage of that.
I prefix the EF-generated classses with "Ef" for clarity.
var personList = new List<Person>();
foreach (var efPerson in EfPersons)
{
var person = new Person
{
Name = efPerson.Name,
StreetsLivedIn = new List<StreetLivedIn>();
}
foreach (var efStreet in efPerson.EfStreetsLivedIn)
{
var street = new StreetLivedIn { Name = efStreet.Name; }
person.StreetsLivedIn.Add(street);
}
personList.Add(person);
}
return View(personList);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.