简体   繁体   中英

Why am I unable to acess properties of my object model?

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() (or First() etc.) to get the result:

var currentUser = (from x in db_tc.Users where x.Id == Convert.ToInt32(User.Identity.Name) select x).SingleOrDefault();
  • 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() and FirstOrDefault() : Same as above, but will return default(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.)

The operation you have here will return a list of matches the DB will return, it is a collection. If you intend on it only returning a single record append .First(); to the end of your linq query.

Also remove this line Users currentUser = new Users(); and add this var currentUser =...

Some more tips from the "good LINQ practices" wagon...

LINQ should "usually" return var, then you convert to the data type you are expecting. Another good practice I have found is to immediately validate the return from LINQ, as any usage without validation is highly exception prone. For instance:

var qUser = (from x in db.Users select x);

if (qUser != null && currentUser.Count() > 0)
{
    List<User> users = (List<User>)qUser.ToList();
    ... process users result ...
}

The not null and count greater than 0 check should be required after each LINQ query. ;)

And don't forget to wrap in try-catch for SqlException!

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