3

I want to set the default value of my primary key of a table in SQL database with newid() via Entity Framework 6 Code First. I know how this is done via code and also found some approaches on stackoverflow, like How to set NewId() for GUID in entity framework

BUT: I have a backup/restore mechanism which inserts the the data not via objects but just as a bulge to the database. So no Entity Framework is used here. That means that a row with a null as guid will be inserted in the SQL database and fails.

It is possible to add the Annotation

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Nullable<Guid> Entity_OID { get; set; }

And this will successfully add NEWSEQUENTIALID() as default value, which does a similar thing as newid() (it adds a new guid which is higher than the recent guids, so you win perfomance because you have a order in the input). But because this is a database which already exist without EF I want to do as few changes as possible. So I'm not excactly happy with NEWSEQUENTIALID(). I would rather like it if it were still just newid(). But I haven't found any Annotation/Mapping for newid() in Entity Framework 6 Code First. And by design all changes to the database have to be done via code. Does anyone know how to add the default value newid() to the row via code?

Thanks in advance!

Community
  • 1
  • 1
Oliver Müller
  • 545
  • 1
  • 5
  • 17
  • Can't you just not use auto generated keys and set the key value in the ctor? I think GUIDs are guaranteed to be unique so it should not matter if they are generated by the database or your code and you should not got into a situation where the same guid is generated for two entities (again - because GUIDs are supposed to be globaly unique) – Pawel Dec 17 '13 at 20:40
  • Yes I can do that and that works for entities created in my code via Buisness Logic. But if I restore from a cbak file via stream where no entities are created, than the database has to generate them. – Oliver Müller Dec 18 '13 at 08:08

2 Answers2

2

It seems that what I tried to do is not possible in Code First. And with the

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Nullable<Guid> Entity_OID { get; set; }

Entity Framework will also generate a new Guid, even if I set a prior to the context.SaveChanges() which is not the behavior I expected.

Oliver Müller
  • 545
  • 1
  • 5
  • 17
0

When you mark a property with DatabaseGeneratedOption.Identity EF gets generated value from DB after every insert operation and sets it to the property. In DB you can do everything such as creating default constraint newid() for the column.

shoma13
  • 317
  • 3
  • 4