Link to home
Create AccountLog in
Avatar of kristian_gr
kristian_grFlag for Norway

asked on

c# Entity Framework Guid as primary key

I'm trying to use c# with the Entity framework to create a simple test project using Guid as a primary key.
I've created the table Test, And changed the primary key from Int32 to Guid.

Then I create the test object, and insert it.
The code should be straight forward (Code 1), but I'm getting an error: {"An error occurred while updating the entries. See the inner exception for details."} -> {"Cannot insert the value NULL into column 'Id', table 'SqlTest.dbo.Tests'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

So I've changed the code to make shure the Guid is created before the object is sendt in. (Code 2)
But I still get the same error.

Any ideas?
The generated sql looks like this:
-- Creating table 'Tests'
CREATE TABLE [dbo].[Tests] (
    [Id] uniqueidentifier  NOT NULL,
    [Value] nvarchar(max)  NULL
);
GO

Code 1:
var con = new SecurityModelContainer();
Test t = new Test { Id = Guid.NewGuid(), Value = "test" };
con.Tests.AddObject(t);
con.SaveChanges();

Code2:
var con = new MyModelContainer();
Test t = new Test();
var _g = Guid.NewGuid();
t.Id = _g;
t.Value = "test";
con.Tests.AddObject(t);
con.SaveChanges();

Open in new window

SOLUTION
Avatar of tovvenki
tovvenki

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account