4

I'm hoping this is a simple goof I did on my end ...

I have a table in my database set up like so:

column name: widget_guid
data type: uniqueidentifier
allow nulls: false
default value: newid()
identity: false
row guid: true

When records are created (via LINQ to SQL) that the values in this field are formatted as a GUID but contain all 0's

My assumption was that when a new record was created, that a guid would be autogenerated for that column, much like an auto-incrementing row id. Is this not true? Any help would be greatly appreciated.

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andy Evans
  • 6,997
  • 18
  • 72
  • 118
  • When you create a record in your application code, are you passing in a Guid or leaving it blank and letting the DB auto-populate? Also, you should try passing in a `Guid.NewGuid()` in your application code to trace it. – jchapa Jan 16 '11 at 02:08
  • i'm wanting the database server to create it using newid(). – Andy Evans Jan 17 '11 at 20:47

2 Answers2

8

You need to check your properties on the GUID column - what you need to make sure is:

  • Auto Generated Values is set to True (so you basically tell Linq-to-SQL that the database will generate the value)

  • Auto-Sync should be set to OnInsert so that your C# object will be populated with the new value after you've called context.SubmitChanges()

With these two settings, you should get the expected behavior: no need to set the GUID on the client side, the database will generate a new value and insert it, and you'll get it back right after the call to .SubmitChanges()

alt text

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • It would be nice if the "Auto Generated Value" property were set to "True" if the UNIQUEIDENTIFIER column's RowGuid property was set to "Yes"... – RoastBeast Feb 11 '14 at 15:52
  • And, unfortunately, it appears this setting would be lost the next time you generate your model data from the database! – Jonathan Wood Apr 28 '17 at 01:30
  • @marc_s, I've been trying to find the above settings on SQL Server 2016 with no luck. How do you find these? – Alex Apr 17 '23 at 11:02
  • 1
    @Alex: that was a setting in Visual Studio, in the Linq-2-SQL datamodel (`.dbml` file) - not in SQL Server. – marc_s Apr 17 '23 at 12:15
1

In your dbml file, set the field to nullable. If it is set to not-nullable, LINQ does not go as far as checking that the field has a default; it simply believes the field non-nullable and will send Guid.Empty causing the 0's.

RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262