C# 无法将值 NULL 插入到 ASP.NET MVC 实体框架中的列中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19727337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot insert the value NULL into column in ASP.NET MVC Entity Framework
提问by Dimo
When trying to use this code:
尝试使用此代码时:
var model = new MasterEntities();
var customer = new Customers();
customer.Sessionid = 25641;
model.Customers.Add(customer);
model.SaveChanges();
I get:
我得到:
{"Cannot insert the value NULL into column 'Sessionid', table 'master.dbo.Column'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
{"无法将值 NULL 插入列 'Sessionid',表 'master.dbo.Column';列不允许为空。INSERT 失败。\r\n语句已终止。"}
The column "Sessionid" is actually the primary key and is marked with [KEY] like this:
“Sessionid”列实际上是主键,并用 [KEY] 标记如下:
public class Customers
{
[Key]
public long Sessionid { get; set; }
public long? Pers { get; set; }
}
So according to thisquestion, it seems as if when the property is marked with [KEY]
, EF ignores my own declaration of Sessionid since it expects the database to assign the value.
所以根据这个问题,似乎当属性被标记为 时[KEY]
,EF 忽略了我自己的 Sessionid 声明,因为它期望数据库分配值。
So how can I solve this? If I remove [KEY]
I get the "entity type has no key defined"
exception...
那么我该如何解决这个问题呢?如果我删除[KEY]
我得到"entity type has no key defined"
异常...
采纳答案by Dimo
I solved it by adding [DatabaseGenerated(DatabaseGeneratedOption.None)]
like this:
我通过添加[DatabaseGenerated(DatabaseGeneratedOption.None)]
这样的方式解决了它:
public class Customers
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Sessionid { get; set; }
public long? Pers { get; set; }
}
回答by Code Monkey
You can configure SQL to auto-generate (and auto-increment) the primary key for the table upon inserts. Then just remove the [Key] in C# and you don't need to set the ID in the application manually, the db will generate it for you.
您可以将 SQL 配置为在插入时自动生成(和自动递增)表的主键。然后只需删除C#中的[Key],您不需要在应用程序中手动设置ID,db会为您生成它。
回答by youHaveAlsoBeenABeginner
I have encountered this problem multiple times while working with Microsoft SQL Server
and I have followed the same way to fix it. To solve this problem, make sure Identity Specificationis set to Yes. Here's how it looks like:
我在使用时多次遇到此问题,Microsoft SQL Server
并且我已按照相同的方法修复它。要解决此问题,请确保将Identity Specification设置为Yes。这是它的样子:
In this way the column number auto incrementsas a primary key normally would.
通过这种方式,列号通常会像主键一样自动递增。
HOW?:right-clickthe table that contains the column, choose Design, selectthe primary key and in Column Propertieswindow find Identity Specificationand set it to Yes.
HOW?:右键单击包含该列的表,选择Design,选择主键并在Column Properties窗口中找到Identity Specification并将其设置为Yes。