简体   繁体   中英

Entity Framework: How to get data from related table (many to many)

I have two tables

LOCATIONS:
Id
Name
OwnerId (FK to Owners table)

PARAMTERS:
Id
LocationId
TypeId
Name
Value

The data is something like:

LOCATIONS
1,'Park',100
2,'Shop',200
PARAMETERS
1,1,'Length',5,200
2,1,'Width',5,100
3,2,'Area',6,100

I want to retrieve the data for all locations that will include all parameters for each location.

I have a query that doesn't work.

_locationsRepository.GetAll()
      .Include(x => x.Owner)
      .Include(x => x.Parameters)
      .ToList();

Running this without including Parameters works fine. There is FK(to Locations table) in Parameters table.

Am I missing something? Would be glad if anyone could help.

You might want to try and add something like:

[InverseProperty("Location")]
public virtual ICollection<Parameters> Parameters { get; set; }

to your Locations table and add

[ForeignKey("LocationId")]
public virtual <Location> Location { get; set; }

to the Parameters table to allow for reverse lookup and help EF generate the foreign key correctly (assuming that you are using CodeFirst of course).

Both of the tags live inside

System.ComponentModel.DataAnnotations;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM