I have the following table:
CREATE TABLE [dbo].[Table1](
Table1ID [uniqueidentifier] NOT NULL,
Name [varchar](200) NOT NULL,
[Date] [smalldatetime] NOT NULL,
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
[Table1ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Table1] ADD CONSTRAINT [DF_Table1_Table1ID] DEFAULT (newid()) FOR [Table1ID]
GO
When I map it using Database first to EF 6.1.3 everything maps fine, generating an Entity Table1s with the Table1ID of type Guid.
When I insert a new item to the database using EF, I can't leave the Table1ID field empty, I have to do the following:
var newRecord = new Table1();
newRecord.Table1ID = Guid.NewGuid();
newRecord.Name = "Test"
newRecord.Date = DateTime.Now;
Manager.Entities.Table1s.Add(newRecord);
Manager.Entities.SaveChanges();
This is sent from a desktop application (WPF), and there will be multiple clients (the application will be in several PCs around the network, all connected to the same DB).
When I create a Guid.NewGuid()
, the Guid is generated locally at the client side and then sent to the database when I do SaveChanges()
.
Doesn't this mean that at some point there is a change for the Guid to be duplicated? (Guid.NewGuid will generate a Guid that is already in the database).
If this could happen, is there a different way to generate a Guid from the database before creating the record?
I tried adding an empty Guid but that didn't help.
I found related questions like these:
But it seems like everyone uses applications that are developed in the Server (e.g. ASP.net Apps), which don't have issues as all the Guid.NewGuid()
are generated in the server.