I’m having a hard time getting the LINQ-syntax.. How can I do this command in a better way?
var user = (from u in context.users
where u.email.Equals(email)
select u).Single();
var pinToUser = (from ptu in context.pintousers
where ptu.user_id.Equals(user.id)
select ptu).Single();
var pin = (from p in context.pins
where p.idpin.Equals(pinToUser.pin_idpin)
select p).Single();
return pin;
As you can see, there’s a table user, a table pintouser and a table pin. Pintouser references user and pin. Is it possible to write something short like “user.pintouser.pin”? I think I have the navigation properties all set up but I’m not sure how to use them properly or if I could make them better by modifying them.
Thanks for reading
Use joins to rewrite everything as a single clean query. If I read your queries properly, this should give you the correct result:
Keep in mind, though, that if this query returns anything other than a single result your code will throw an Exception.
If you want to handle the possibility of getting one or no rows then you should use
SingleOrDefault().If you want to handle the possiblity of getting any number of rows then you should really use
FirstOrDefault().