Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read GUID value from database

Please see the code:

var roleId = from r in _eStoreDbContext.UserModel where r.UserName == userName select r.RoleId;
if(string.IsNullOrEmpty(roleId.ToString()))
{
    return false;
}

Guid g = new Guid();
Guid.TryParse(roleId.ToString(), out g);

While executing query I'm getting Guid value, But converting it into GUID, getting 000XXXX. Please find attached the debugging screen.

enter image description here

like image 979
Jobi Avatar asked Jun 16 '26 05:06

Jobi


2 Answers

roleId is IQueryable<T> (that is just query definition, not result of query execution, and definitely not first item from results). When you call roleId.ToString() you get type name, which is obviously cannot be parsed to Guid.

I think you need to get first or default roleId from database:

var roleId = _eStoreDbContext.UserModel 
                 .Where(u => u.UserName == userName)
                 .Select(u => u.RoleId)
                 .FirstOrDefault();

Further actions depend on what type RoleId has. If its nullable Guid, then you can compare roleId with null to check if id was found. If its non-nullable, then compare result with Guid.Empty.

like image 172
Sergey Berezovskiy Avatar answered Jun 18 '26 20:06

Sergey Berezovskiy


Your problem is, judging from the screenshot, is that var roleId variable is actually an IEnumerable<string>, and not a single string! What you need to do is call .SingleOrDefault() on the result of your query, then you can (try)parse is with Guid.TryParse, i.e.:

var roleId = (from r in _eStoreDbContext.UserModel 
              where r.UserName == userName select 
              r.RoleId).SingleOrDefault();

...

like image 25
Igal Tabachnik Avatar answered Jun 18 '26 18:06

Igal Tabachnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!