這是我的代碼有:「無法插入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