INSERT 在 EF 4.1 Code First 数据库上失败
我使用带有 MVC3 工具更新的 Visual Studio 2010 SP1 和 EF 4.1 Code First 来构建应用程序的数据库。
在本地和本地数据库上进行测试时,数据库 CRUD 操作运行良好。直到我将数据库迁移到 Web 主机的 SQL Server 2008 R2 并在连接字符串中定位该托管数据库后,所有 INSERT 操作才会失败。
每当我尝试添加新记录时,都会收到此错误: [I]Cannot insert the value NULL into columns 'Id', table 'DB_23378_bloomlmsdata.dbo.Courses';列不允许为空。插入失败。该语句已终止。[/I]
我的数据模型都指定了一个主标识键,如下所示:
[Key]
public int Id {get; set;}
...
在搭建的本地数据库中,我在每个表中看到一个不可为空的主标识键。
我在某处读到实体框架,当对数据库执行 INSERT 操作时,它会首先尝试插入一条以空值作为主键的记录。我不知道如何覆盖这种行为。此外,这似乎不是一个常见问题,人们通常只有在使用与 IDENTITY 密钥不同的东西时才会遇到这个问题。根据记录,在 EF 4.1 发布之前,我在使用 EF CodeFirst CTP5 时也遇到了同样的问题。
我已经解决这个问题 4 周了。我的网络主机与我在应用程序和数据库中使用的技术保持同步。当我尝试寻求帮助时,他们告诉我这是一个编码问题,但我的代码检查正常。任何想法将不胜感激。
I am using Visual Studio 2010 SP1 with MVC3 Tools Update, and EF 4.1 Code First to scaffold my application's database.
Database CRUD operations work fine when testing locally and on a local database. It is not until I migrate the database to web host's SQL Server 2008 R2 and target that hosted database in my connection string that all INSERT operations fail.
Whenever I try to add a new record I get this error: [I]Cannot insert the value NULL into column 'Id', table 'DB_23378_bloomlmsdata.dbo.Courses'; column does not allow nulls. INSERT fails. The statement has been terminated.[/I]
My data models all specify a Primary Identity Key like so:
[Key]
public int Id {get; set;}
...
And in the local database that gets scaffolded, I see a non-nullable Primary Identity Key in each table.
I read somewhere that Entity Framework, when performing an INSERT operation to the database it will first try to insert a record with a null value as the Primary Key. I do not know how to override this behaviour. Also, this does not seem to be a common problem and people usually only run in to this when they use something different than an IDENTITY key. For the record, I had the same problem with EF CodeFirst CTP5 before EF 4.1 was released.
I have been troubleshooting this for 4 weeks.. My web host is up to date with the technology I am using in my application and database. When I try to get help, they are telling me it is a coding issue but my code checks out. Any ideas would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查 Id 列的 IsIdentity 属性,它应该设置为 yes。 EF 不会在插入时传递标识列的值,因为它应该由数据库自动生成。
Check the IsIdentity property of the Id column, it should be set to yes. EF doesn't pass a value for the identity column on an insert because it should be auto-generated by the database.