简体   繁体   English

带有非空值的“无法将值NULL插入列”

[英]“Cannot insert the value NULL into column” with a non-null value

This is the code I have: 这是我的代码:

Controller action method: 控制器动作方法:

[HttpPost]
public ActionResult Create(Goal goal)
{
    if (ModelState.IsValid)
    {
        repository.SaveGoal(goal);
        return View("Index");
    }
    else
    {
        return View(goal);
    }
}

Model: 模型:

public class Goal
{
    [Required]
    public int GoalId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [HiddenInput(DisplayValue = false)]
    public decimal Latitude { get; set; }

    [Required]
    [HiddenInput(DisplayValue = false)]
    public decimal Longitude { get; set; }

    [Required]
    public bool IsPrivate { get; set; }
}

Repository: 库:

public class EFGoalRepository : IGoalRepository
{
    private EFDbContext context = new EFDbContext();

    public IQueryable<Goal> Goals
    {
        get { return context.Goals; }
    }

    public void SaveGoal(Goal goal)
    {
        context.Goals.Add(goal);
        context.SaveChanges(); // the line which causes the exception
    }
}

The problem: When I try to save a new Goal object with GoalId set to 0 , I get the following error: 问题:当我尝试将GoalId设置为0的新Goal对象保存时,出现以下错误:

Cannot insert the value NULL into column 'GoalId', table 'TravelGoals.dbo.Goals'; 无法将值NULL插入表'TravelGoals.dbo.Goals'的'GoalId'列中; column does not allow nulls. 列不允许为空。 INSERT fails. INSERT失败。 The statement has been terminated. 该语句已终止。

I'm still new at ASP.NET MVC, but I believe this worked when I tried it a month ago with a different project. 我还是ASP.NET MVC的新手,但是我相信当我一个月前在另一个项目中尝试过该方法时,这种方法行之有效。

All the values in my Goal object are valid (non- null , Name is of correct length). 我的Goal对象中的所有值都是有效的(非nullName的长度正确)。 The GoalId property is set to 0 , so it is not null either. GoalId属性设置为0 ,因此也不为null I thought that Entity Framework would automatically assign a value to it. 我认为实体框架会自动为其分配一个值。

What can I do to make this work? 我该怎么做才能使这项工作?

What I needed to do was setting the column as identity in SQL Server. 我需要做的是将列设置为SQL Server中的标识。

Probably the simplest way to do this (assuming you're using Visual Studio): 可能是最简单的方法(假设您使用的是Visual Studio):

  • Open the SQL Server Object Explorer 打开SQL Server对象资源管理器
  • Double-click the table you want to edit (or right-click and select View Designer) 双击要编辑的表(或右键单击并选择“视图设计器”)
  • Open the Properties window 打开属性窗口
  • Select the column in the Identity Column property as shown below 选择“标识列”属性中的列,如下所示

显示标识列属性的属性窗口

Problem is GoalId is not identity.Put this attribut on GoalId 问题是GoalId不是身份。将此属性放在GoalId

[Key]
public int GoalId { get; set; }

If your EF version is lower than 5 use this: 如果您的EF版本低于5,请使用以下命令:

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int GoalId { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM