EF6.1 newsequentialid with ability to set value manually

£可爱£侵袭症+ 提交于 2019-12-11 06:37:38

问题



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; }

Which results in perfect SQL:

[Id] [uniqueidentifier] NOT NULL DEFAULT (newsequentialid()) 

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?


回答1:


If you want to set manually your Guid Id property then remove DatabaseGenerated attribute:

[Key] 
public Guid Id { get; set; }

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.



来源:https://stackoverflow.com/questions/40598817/ef6-1-newsequentialid-with-ability-to-set-value-manually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!