![](/img/trans.png)
[英]“cannot insert null value to primary key” error while trying to insert a non-null value
[英]“Cannot insert the value NULL into column” with a non-null value
這是我的代碼:
控制器動作方法:
[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
}
}
問題:當我嘗試將GoalId
設置為0
的新Goal
對象保存時,出現以下錯誤:
無法將值NULL插入表'TravelGoals.dbo.Goals'的'GoalId'列中; 列不允許為空。 INSERT失敗。 該語句已終止。
我還是ASP.NET MVC的新手,但是我相信當我一個月前在另一個項目中嘗試過該方法時,這種方法行之有效。
我的Goal
對象中的所有值都是有效的(非null
, Name
的長度正確)。 GoalId
屬性設置為0
,因此也不為null
。 我認為實體框架會自動為其分配一個值。
我該怎么做才能使這項工作?
我需要做的是將列設置為SQL Server中的標識。
可能是最簡單的方法(假設您使用的是Visual Studio):
問題是GoalId
不是身份。將此屬性放在GoalId
[Key]
public int GoalId { get; set; }
如果您的EF版本低於5,請使用以下命令:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int GoalId { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.