سؤال

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!

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top