DatabaseGeneratedOption.Identity不生成ID [英] DatabaseGeneratedOption.Identity not generating an Id
问题描述
首先使用EntityFramework代码,我创建了一个简单的Foo
表.这是我的实体:
Using EntityFramework code-first, I've created a simple Foo
table. Here's my entity:
public class Foo
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual string Id { get; set; }
public virtual string Name { get; set; }
}
但是,每当我尝试插入新行时,都会得到一个Cannot insert the value NULL into column 'Id'
.为什么添加DatabaseGenerated
属性时会发生这种情况?删除和重新创建我的表没有任何区别.
However whenever I try to insert a new row, I get a Cannot insert the value NULL into column 'Id'
. Why is this happening when I've added a DatabaseGenerated
attribute? Deleting and recreating my table makes no difference.
推荐答案
SQL Server不支持string
列类型的标识. (您希望这样的字符串看起来如何?)要使其正常工作,您可以-例如-在SQL Server中添加一个计算列/用户定义的函数,该函数可格式化普通int身份列中的字符串-如此处.
Identities for string
column types are not supported with SQL Server. (How do you expect such a string to look like?) To get this working you could - for example - add a computed column/user defined function in SQL Server that formats a string from an ordinary int identity column - as shown here.
这篇关于DatabaseGeneratedOption.Identity不生成ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!