For some odd reason, I am unable to access the properties of this object EVEN if I cast it as its model type. Does anyone have an idea as to why? (It may be obvious, but I’m pretty new to C# so please be patient! :o) )
Users currentUser = new Users();
currentUser = (from x in db_tc.Users where x.Id == Convert.ToInt32(User.Identity.Name) select x);
When I call currentUser, I am only able to access the CRUD methods and a List<Users> property called usrList. I didn’t create the list definition, so I imagine this is some piece of the Entity framework that is automagically created.
I did try casting currentUser with (Users) prior to the entity query, it didn’t help at all.
That’s because you’ve only created the query, you haven’t actually executed it. Add
Single()(orFirst()etc.) to get the result:Single(): Gets the first element of the sequence, but will throw an exception if no element is found or if the sequence has more than one element.First(): Gets the first element of the sequence, but will throw an exception if no element is found.SingleOrDefault()andFirstOrDefault(): Same as above, but will returndefault(T)instead of throwing on the empty sequence.This “deferred execution” aspect of LINQ is probably the most difficult part to understand. The basic idea is that you can build up a query using the query operations (
Where(),Select(), etc.), and then you can execute that query to actually get its results, using one of the non-deferred execution operations (Single(),ToList(), etc.)