这是我的代码有:“无法插入NULL值插入列” 与非空值
控制器的操作方法:
[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
}
}
问题:W母鸡我尝试使用GoalId
集保存新Goal
对象0
,我得到以下错误:
Cannot insert the value NULL into column 'GoalId', table 'TravelGoals.dbo.Goals'; column does not allow nulls. INSERT fails. The statement has been terminated.
我还是新的ASP.NET MVC,但我相信这工作时,我一个月的试了一下以前有不同的项目。
我的Goal
对象中的所有值均有效(非null
,Name
的长度正确)。 GoalId
属性设置为0
,所以它也不是null
。我认为Entity Framework会自动为它分配一个值。
我该怎么做才能做到这一点?
你配置ID是一个数据库生成列时,你在EF中创建表? – Liath
显然我没有。我将该列设置为SQL Server中的身份,现在用作魅力。谢谢! – Lasooch