Hi I have an SQL Server table as below
CREATE TABLE [dbo].[Location](
[LocationUID] [uniqueidentifier] NOT NULL,
[Code] [char](10) NULL,
[Type] [char](1) NOT NULL,
[FullName] [nvarchar](150) NULL,
CONSTRAINT [PK_Location] PRIMARY KEY CLUSTERED
(
[LocationUID] ASC
)
ALTER TABLE [dbo].[Location] ADD CONSTRAINT [DF_Location_LocationUID] DEFAULT (newid()) FOR [LocationUID]
I have a C# WCF service in .NET4 using EF4 to insert into the Table location. This is the code that does it
//create country
country = new Location()
{
FullName = CountryName,
Type = "C",
Diaretics = CountryName,
Code = CountryCode
};
dbContext.AddToLocations(country);
dbContext.SaveChanges();
But when I run the service the code falls over at dbContext.SaveChanges() with Error
Violation of PRIMARY KEY constraint ‘PK_Location’. Cannot insert duplicate key in object ‘dbo.Location’.
The statement has been terminated.
I thought this is impossible to happen with the way the default value is set on LocationUID field with NewUID() and the configuration of primary key.
Any help would be appreciated
Set the
StoreGeneratedPatterntoIdentityon the GUID PK property.Ref:
Working with Entity Keys
Tip 19 – How to use Optimistic Concurrency with the Entity Framework
Using uniqueidentifier SQL column type with Entity framework
Entity Framework 4 Primary Key as GUID and autogeneration