简体   繁体   中英

Converting String to System.guid c#

I am trying to retrieve a client's name based on the Account GUID, using sql and c#.

static DataClasses1DataContext dbDataClasses = new DataClasses1DataContext();
    static void Main(string[] args)
    {

        var accountList = from accounts in dbDataClasses.ACCOUNTs where   accounts.AccountGUID.ToString() = "e8d82d5d-b7bd-4b24-a7fe-ef050921e960"
                          select accounts;

        foreach (ACCOUNT temp in accountList)
        {
            Console.WriteLine("Account Name: " + temp.Name + " Account GUID: " + temp.AccountGUID);
        }

    }

However, I receive an error saying "Cannot implicitly convert type 'string' to 'System.guid'

Any help would be appreciated. Thanks

Take a look at the documentation for the Guid class . There's a constructor that takes a string and there's also the Parse static method

use

Guid.Parse()

or Guid.ParseExact() on your string before using it in :

where accounts.AccountGUID= "e8d82d5d"

it should be like :

 where accounts.AccountGUID= Guid.Parse("e8d82d5d")

There are 2 ways you can do it

Assuming all Id's are in a valid format

Guid accountId = Guid.Parse(accountIdString);

assumes that your accountIdString is always in a validated format, and if it isn't it will throw an exception

Assuming Id's might be in an invalid format

Guid accountId;
bool parseCheck = Guid.TryParse(accountIdString, out accountId);

will attempt to parse your accountIdString, and return true or false to parseCheck based on whether it succeeded or not. If it succeeded it will also store the parsed Guid as accountId

Which one you use depends on if you know every Id is in valid Guid format or not.

You need to convert the Guid to string before comparing to a string:

var accountList = from accounts in dbDataClasses.ACCOUNTs where accounts.AccountGUID.ToString()== "e8d82d5d"

However "e8d82d5d" is not a guid, so you will never see any results from this query.

static DataClasses1DataContext dbDataClasses = new DataClasses1DataContext();
    static void Main(string[] args)
    {
        Guid someGuid;
        if(Guid.TryParse("e8d82d5d", out someGuid))
        {
             var accountList = from accounts in dbDataClasses.ACCOUNTs where accounts.AccountGUID= someGuid
                          select accounts;

            foreach (ACCOUNT temp in accountList)
            {
                 Console.WriteLine("Account Name: " + temp.Name + " Account GUID: " + temp.AccountGUID);
            }
        }
        else
        {
            //error handle
        }


   }

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