C
C#2y ago
linqisnice

❔ accessing collections via principal entity vs directly on dbset

what is generally preferred if i want the accommodations of a listing (WITH resource ownership check included, so firstasync is intentional here)? s Doing this:
var listing = await _dbContext.Listings
.AsSplitQuery()
.Include(x => x.Accommodations).ThenInclude(x => x.Inventory)
.FirstAsync(x => x.Id == request.ListingId && x.Host.UserId == currentUserId);

var accommodations = listing.Accommodations... // just an example
var listing = await _dbContext.Listings
.AsSplitQuery()
.Include(x => x.Accommodations).ThenInclude(x => x.Inventory)
.FirstAsync(x => x.Id == request.ListingId && x.Host.UserId == currentUserId);

var accommodations = listing.Accommodations... // just an example
or actually querying accommodations directly? I find that the above seems better, since it will immediately return the request if the user does not have access. whereas if we query accommodations, it's going to reutnr an empty list and then continue I guess my question pertains in general to resource ownership and accessing a collection items via prinicipal entity vs directly on the dbset. My strategy is generally to use firstasync since if the user is not the owner of the listing, they have likely tampered with the inspector or some such to finagle the resource
5 Replies
TravestyOfCode
I include the relations if I'm going to need them instead of separately. Do you need to differentiate between a ListingId not being found and the UserId not being the currentUserId? FirstAsync will throw an exception if the it doesn't find a match on the whole condition. Also, I tend to use SingleOrDefault when querying where I know there should be only one or none.
linqisnice
linqisniceOP2y ago
@TofCodesingle needs to check the entire collection to ensure there are no other records, so performance wise first/firstordefault is faster the idea is for firstasync to either throw an exception if listingId doesn't exist or if the resource does not belong to the user trying to access it, because the only way listingId is even retrieved by the user is if it exists, so it should always exist
TravestyOfCode
Do you only need to get the Accommodations and Inventory and don't care about the Listings?
linqisnice
linqisniceOP2y ago
well they belong to the listing, and it'st for resource ownership check as well
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server