我首先使用dotConnect for MySQL实现实体框架代码。
在向上下文添加对象后调用context.SaveChanges()
时出现以下错误:
DbUpdateException :
更新条目时发生错误。有关详细信息,请参阅内部异常。内部例外:
UpdateException:更新条目时发生错误。有关详细信息,请参阅内部异常。内部例外: EntityCommandCompilationException:准备命令定义时发生错误。有关详细信息,请参阅内部异常。“}
内部例外:
NotSupportedException:{“空插入语句。”}
在我将项目添加到DbContext
DbContext
奇怪的是,当我添加其所有内容时,它已成功添加,但当我添加对象本身时,我收到此错误。
这行代码失败:
context.TournamentTables.Add(tournamentTable);
虽然这个完美无缺:
tournamentTable.Columns.ForEach(column =>
{
column.Cells.ForEach((cell) => context.TournamentCells.Add(cell));
context.TournamentColumns.Add(column);
});
这是我尝试添加的对象:
public class TournamentTable //: IEnumerable<TournamentColumn>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
public List<TournamentColumn> Columns { get; set; }
public TournamentTable()
{
Columns = new List<TournamentColumn>();
}
public void AddColumn(int index, TournamentColumn column)
{
Columns.Insert(index, column);
}
public void RemoveColumn(int index)
{
Columns.RemoveAt(index);
}
/// <summary>
/// Add a tournament cell at the top of the column.
/// </summary>
/// <param name="column"></param>
public void AddColumn(TournamentColumn column)
{
Columns.Add(column);
}
/// <summary>
/// Returns the tournament column at the index specified.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
[NotMapped]
public TournamentColumn this[int index]
{
get { return Columns[index]; }
}
/// <summary>
/// Returns the tournament cell at the index specified.
/// </summary>
/// <param name="columnIndex"></param>
/// <param name="cellIndex"></param>
/// <returns></returns>
[NotMapped]
public TournamentCell this[int columnIndex, int cellIndex]
{
get { return Columns[columnIndex][cellIndex]; }
set
{
Columns[columnIndex][cellIndex] = value;
}
}
}
请注意,锦标赛表ID默认为0,如果Id声明为“int?”比它将为null。我已经尝试了两种情况,并且自己设置了id,但它仍然失败。
答案 0 :(得分:0)
我认为你是以错误的方式添加列。
基本上,你不需要这个:
tournamentTable.Columns.ForEach(column =>
{
column.Cells.ForEach((cell) => context.TournamentCells.Add(cell));
context.TournamentColumns.Add(column);
});
实体框架为您做到了这一点。将所有列添加到锦标赛表后,您只需要调用context.TournamentTables.Add(tournamentTable)
。