无法插入NULL值插入列在ASP.NET MVC实体框架 [英] Cannot insert the value NULL into column in ASP.NET MVC Entity Framework

查看:209
本文介绍了无法插入NULL值插入列在ASP.NET MVC实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试使用此code:

When trying to use this code:

var model = new MasterEntities();

var customer = new Customers();
customer.Sessionid = 25641;

model.Customers.Add(customer);
model.SaveChanges();

我得到:

{无法插入NULL值插入列'SESSIONID',表
  master.dbo.Column';列不允许空值。插
  失败。\\ r \\ n此语句已终止。}

{"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."}

列的SessionID其实是主键,标有[KEY]是这样的:

The column "Sessionid" is actually the primary key and is marked with [KEY] like this:

 public class Customers
    {   
        [Key]
        public long Sessionid { get; set; }
        public long? Pers { get; set; }
    }

所以,根据<一个href=\"http://stackoverflow.com/questions/18470736/cannot-insert-the-value-null-into-column-roleid-mvc4-simple-membership\">this问题,它好像当属性被标记 [KEY] ,EF忽略了我自己的SessionID的声明,因为它期望的数据库分配的值。

So according to this question, 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] 我得到的实体类型没有定义键例外...

So how can I solve this? If I remove [KEY] I get the "entity type has no key defined" exception...

推荐答案

我解决它通过添加 [DatabaseGenerated(DatabaseGeneratedOption.None)] 是这样的:

I solved it by adding [DatabaseGenerated(DatabaseGeneratedOption.None)] like this:

public class Customers
    {   
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public long Sessionid { get; set; }
        public long? Pers { get; set; }
    }

这篇关于无法插入NULL值插入列在ASP.NET MVC实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆