“无法使用非空值将值NULL插入列”

时间:2014-07-17 09:41:51

标签: c# entity-framework asp.net-mvc-4

这是我的代码:

控制器动作方法:

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

型号:

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; }
}

存储库:

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
    }
}

问题:当我尝试保存设置为Goal的{​​{1}}的新GoalId对象时,出现以下错误:

  

无法将值NULL插入“GoalId”列,表格“TravelGoals.dbo.Goals”;列不允许空值。 INSERT失败。   声明已经终止。

我仍然是ASP.NET MVC的新手,但我相信这在一个月前用不同的项目尝试过时有用。

我的0对象中的所有值都有效(非Goalnull长度正确)。 Name属性设置为GoalId,因此它也不是0。我认为实体框架会自动为其分配一个值。

我可以做些什么来完成这项工作?

2 个答案:

答案 0 :(得分:3)

我需要做的是在SQL Server中将列设置为标识。

这可能是最简单的方法(假设你正在使用Visual Studio):

  • 打开SQL Server对象资源管理器
  • 双击要编辑的表(或右键单击并选择“视图设计器”)
  • 打开“属性”窗口
  • 选择Identity Column属性中的列,如下所示

Properties window showing the Identity Column property

答案 1 :(得分:1)

问题是GoalId不是身份。请在GoalId

上添加此属性
[Key]
public int GoalId { get; set; }

如果您的EF版本低于5,请使用:

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