EF6.1 newsequentialid,具有手动设置值的功能 [英] EF6.1 newsequentialid with ability to set value manually
问题描述
我是EF(v6.1)的新手。尝试使用Code-First方法。
我希望在SQL服务器端( newsequentialid()
)上生成Id列,但是具有覆盖这些值的能力。
我的代码:
I'm new to EF(v6.1). Trying to use Code-First approach.
I would like to have Id column to be generated on SQL server side (newsequentialid()
), however with ability to override those values.
My code:
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
哪些导致完美的SQL:
Which results in perfect SQL:
[Id] [uniqueidentifier] NOT NULL DEFAULT (newsequentialid())
但是,EF忽略了我将设置为 Id
属性的值,并将null传递给SQL。基本上,以下测试将无法正常工作:
However EF simply ignores any value I would set to Id
property and pass null to SQL. Essentially follwing test wouldn't work:
MyContext context = new MyContext();
MyClass item = new MyClass();
Guid id = Guid.NewGuid();
item.Id = id;
context.MyTable.Add(item);
context.MyTable.Create();
context.SaveChanges();
Assert.AreEqual(item.Id, id);
我应该怎么做才能使我的测试工作?
What should I do to make my test work?
推荐答案
如果要手动设置您的 Guid
Id
属性然后删除 DatabaseGenerated
属性:
If you want to set manually your Guid
Id
property then remove DatabaseGenerated
attribute:
[Key]
public Guid Id { get; set; }
如果将PK属性配置为 Identity
,该值将在您的DB中生成。此外,您不需要将此属性标记为必需
,默认情况下需要PK属性。
If you configure your PK property as Identity
, the value will be generated in your DB.Also, you don't need to mark this property as Required
, PK properties are required by default.
这篇关于EF6.1 newsequentialid,具有手动设置值的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!