简体   繁体   English

newid()与实体框架6代码优先

[英]newid() with Entity Framework 6 Code First

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. 我想通过Entity Framework 6 Code First在newid()中设置SQL数据库中表的主键的默认值。 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 我知道这是如何通过代码完成的,并且还在stackoverflow上找到了一些方法,比如如何在实体框架中为GUID设置NewId()

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. 这意味着将一个null为guid的行插入SQL数据库并失败。

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). 这将成功添加NEWSEQUENTIALID()作为默认值,这与newid()类似(它添加了一个高于最近guid的新guid,因此你在输入中有一个订单就赢得了性能)。 But because this is a database which already exist without EF I want to do as few changes as possible. 但是因为这是一个已经存在而没有EF的数据库,我希望做尽可能少的更改。 So I'm not excactly happy with NEWSEQUENTIALID(). 所以我对NEWSEQUENTIALID()并不满意。 I would rather like it if it were still just newid(). 如果它仍然只是newid(),我宁愿喜欢它。 But I haven't found any Annotation/Mapping for newid() in Entity Framework 6 Code First. 但我没有在Entity Framework 6 Code First中找到newid()的任何注释/映射。 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? 有谁知道如何通过代码将默认值newid()添加到行?

Thanks in advance! 提前致谢!

It seems that what I tried to do is not possible in Code First. 似乎我在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. 实体框架也会生成一个新的Guid,即使我在context.SaveChanges()之前设置了一个不是我预期的行为。

When you mark a property with DatabaseGeneratedOption.Identity EF gets generated value from DB after every insert operation and sets it to the property. 使用DatabaseGeneratedOption.Identity标记属性时,EF会在每次插入操作后从DB获取生成的值并将其设置为属性。 In DB you can do everything such as creating default constraint newid() for the column. 在DB中,您可以执行所有操作,例如为列创建默认约束newid()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM