出于某种原因,这段代码返回以下异常:
An error occurred while updating the entries. See the inner exception for details.
Inner Exception: Cannot insert the value NULL into column 'Id',
table 'aspnet-Webate.dbo.Tasks'; column does not allow nulls. INSERT fails.\r\n
The statement has been terminated
变量 tasks 是一个具有这种形式的字符串:
(task1, task2, task3, task4)
诊断程序在控制台中显示这 4 个任务中的每一个都没有问题。没有一个数组索引为空或空白
string[] taskArr = null;
tasks = tasks.Substring(1, tasks.Length - 2); //remove the starting and ending parenthesis
tasks = tasks.ToLower();
tasks = tasks.Replace(" ", "");
taskArr = tasks.Split(new char[] { ',' });
foreach (string t in taskArr)
{
System.Diagnostics.Debug.WriteLine("t="+t);
if (t != null && t != "")
{
Task task = db.Tasks.Find(t);
if (task == null)
{
task = new Task { Id = t };
db.Tasks.Add(task);
}
}
}
try
{
db.SaveChanges(); //save task changes before trying to save role
}
catch (Exception e)
{
throw exception code
}
对于 EntityFramework 可能试图将空值插入数据库的原因,还有其他解释吗?
这是任务模型:
using System;
using System.Collections.Generic;
public partial class Task
{
public Task()
{
this.Roles = new HashSet<Role>();
}
public string Id { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
该类由 Visual Studio 2012 的 ADO.NET 实体数据模型功能生成,没有其他部分实现