Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework populating uniqueidentifier with value "00000000-0000-0000-0000-000000000000"

In my WCF service I am using Entity Framework .NET 4.0, in my database i have this table:

CREATE TABLE [dbo].[Tracking](
    [TrackingID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,   
    ...
 CONSTRAINT [PK_Tracking] PRIMARY KEY CLUSTERED 
(
    [TrackingID] ASC
)
) ON [DATA]
ALTER TABLE [dbo].[Tracking] ADD  CONSTRAINT [DF_Tracking_TrackingID]  DEFAULT (newid()) FOR [TrackingID]
GO

when i insert a record Entity framewrok has prepopulated the TrackingID as "00000000-0000-0000-0000-000000000000". I have setting field property to be Computed and Identity bu no such luck any ideas: here is my code snippet:

using (var context = new DB.PTLEntities())
{
     var tracking = new DB.Tracking();       
     context.Trackings.AddObject(tracking);
     context.SaveChanges();
     trackingID = tracking.TrackingID;
}
like image 697
greektreat Avatar asked Jun 21 '12 21:06

greektreat


2 Answers

Looks like EF doesnt think this column is an identity column so its putting in default(Guid). Take a look here for some details on making a guid an identity column (it actually goes through your exact example) http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

like image 81
Not loved Avatar answered Sep 19 '22 19:09

Not loved


I got same issue. Following solution worked for me.

There is a need to change the StoreGeneratedPattern value for the property in the EF designer. Set it to Identity. This will cause EF to avoid setting the value on an insert, then capture it after the insert is complete.

If your EF version is 4, then you may have trouble with this using the designer only. You may have to edit the .edmx manually and set the StoreGeneratedPattern in the storage model itself.

Example:

< Property Name="EmpId" Type="uniqueidentifier" Nullable="false" StoreGeneratedPattern="Identity" />
like image 38
Anant Dhas Avatar answered Sep 17 '22 19:09

Anant Dhas