3

I have a table like

CREATE TABLE Partners 
(
    id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
    name NVARCHAR(50) NOT NULL,
    email NVARCHAR(254) NOT NULL, -- 254 is optimal length according to http://stackoverflow.com/questions/1199190/what-is-the-optimal-length-for-an-email-address-in-a-database
    PRIMARY KEY (id)
);

and a simple stored procedure:

CREATE PROCEDURE GetPartnersWithIds
AS
    SELECT id, name 
    FROM Partners;

The result of which I'm trying to reading into a List<PartnerWithId> where PartnerWithId is defined by

public class PartnerWithId
{
    public Guid Id { get; set; }
    public string Name { get; set; }
} 

My method for doing so is

    public List<PartnerWithId> GetPartners ( )
    {
        List<PartnerWithId> Partners = new List<PartnerWithId>();

        using (SqlCommand cmd = new SqlCommand("GetPartnersWithIds", this._Conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            this._Conn.Open();

            using (SqlDataReader dataReader = cmd.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    Partners.Add(new PartnerWithId {
                        Id = (Guid)dataReader.GetString(0),
                        Name = dataReader.GetString(1)
                    });
                }
            }
            this._Conn.Close();
        }
        return Partners;
    }

but I'm getting an error

Cannot convert type string to System.Guid

on chunk (Guid)dataReader.GetString(0) (which was really just a guess). What is the correct way to get this value?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user5648283
  • 5,913
  • 4
  • 22
  • 32
  • You are getting that error since you are using the `GetString()` method of the `DataReader` class. you should use `GetGuid()` instead. – Zohar Peled Feb 04 '16 at 05:19

1 Answers1

3

Instead of cast try creating Guid with Guid string or use Guid.Parse

 Id = new Guid(dataReader.GetString(0)),

or better to use DataReader.GetGuid() directly instead of getting string and converting into Guid.

 Id = dataReader.GetGuid(0),
Adil
  • 146,340
  • 25
  • 209
  • 204