Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a c# datatable object with GUID as identifier?

Tags:

c#

datatable

is this possible instead of an incrementing ID number, I have GUID in the code instead?

like image 809
Martin Ongtangco Avatar asked Dec 04 '25 10:12

Martin Ongtangco


2 Answers

Certainly, check here:

http://msdn.microsoft.com/en-us/library/system.data.datatable.primarykey(VS.71).aspx

   // Create a new DataTable and set two DataColumn objects as primary keys.
   DataTable myTable = new DataTable();
   DataColumn[] keys = new DataColumn[1];
   DataColumn myColumn = new DataColumn();
   myColumn.DataType = System.Type.GetType("System.Guid");
   myColumn.ColumnName= "ID";
   // Add the column to the DataTable.Columns collection.
   myTable.Columns.Add(myColumn);
   keys[0] = myColumn;
   // Set the PrimaryKeys property to the array.
   myTable.PrimaryKey = keys;
like image 58
CSharper Avatar answered Dec 07 '25 16:12

CSharper


One option is to normally have the value of the primary key as NEWID() to assign GUID to a variable declared as the uniqueidentifier data type

The other option is to have sequential GUIDs using this NEWSEQUENTIALID() function available in sqlserver. However MSDN states: If privacy is a concern, do not use this function. It is possible to guess the value of the next generated GUID and, therefore, access data associated with that GUID.

Example of SqlQuery using newid()

CREATE TABLE cust
(
 CustomerID uniqueidentifier NOT NULL
   DEFAULT newid(),
 Company varchar(30) NOT NULL,
 ContactName varchar(60) NOT NULL, 
 Address varchar(30) NOT NULL, 
 City varchar(30) NOT NULL,
 StateProvince varchar(10) NULL,
 PostalCode varchar(10) NOT NULL, 
 CountryRegion varchar(20) NOT NULL, 
 Telephone varchar(15) NOT NULL,
 Fax varchar(15) NULL
)
like image 36
K Singh Avatar answered Dec 07 '25 17:12

K Singh



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!