简体   繁体   中英

How do i get all child records in mvc5 using linq

I have a database structure

users
 --username
 --ProfileId
 --passwordhash

Profile
 --Id
 --name

Drives
 --id
 -- name

userDrives
 --Id
 --ProfileId
 --DriveId

I am looking to get all the drives of the current logged in user. I normally would have written a stored procedure to get the desired results. But i am trying to use linq for the first time(learning) and getting back into asp.net programming after years of working on other technologies.

Please bear with if the question is very newbieish

How to get all drives for the current user?

When using Entity Framework you can add navigation properties to your entities. Navigation properties represent relationships between entities. Here you have a one-to-many relationship between Drive and Profile, you can add navigation properties to your entities like this:

  • add ICollection<Drive> property to Profile entity.
  • add Profile property to Drive entity.
  • add User property to Profile entity.
  • add Profile property to User entity.

When you have an instance of an user, you can use user.Profile.Drives to retrieve it's drives (here Drives is ICollection<Drive> ). You can also use it to add new drives to that user, don't forget to call SaveChanges at the end. When using navigation properties you should take care that EF is able to create proxies for you entities, otherwise they will be null since EF cannot do lazy loading on your instances. If you want more information about this subject you should look for Entity Framework Proxies .

You can do something similar to:

var result=(from u in user Join ud in userdrives On u.ProfileId equals ud.ProfileId Join d in drives On ud.DriveId equals d.id Where u.username == loggedinUsername Select d).ToList ();

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