【发布时间】:2015-11-29 21:11:46
【问题描述】:
我正在尝试使用实体框架将记录添加到表中,当我在 _entities.SaveChanges(); 上执行此方法时得到 DbUpdateException:
public Player CreatePlayer(int fideNumber, string name, string surname, DateTime birthDate, double? rating = null)
{
var player = _entities.Players.Add(new Player
{
Id = fideNumber,
BirthDate = new DateTime(birthDate.Year, birthDate.Month, birthDate.Day),
Name = name,
Surname = surname,
Rating = 1500
});
_entities.SaveChanges();
return player;
}
我的Player 模型如下所示:
public partial class Player
{
public Player()
{
this.Tournaments = new HashSet<Tournament>();
this.GamesAsWhite = new HashSet<Game>();
this.GamesAsBlack = new HashSet<Game>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public System.DateTime BirthDate { get; set; }
public Nullable<double> Rating { get; set; }
public virtual ICollection<Tournament> Tournaments { get; set; }
public virtual ICollection<Game> GamesAsWhite { get; set; }
public virtual ICollection<Game> GamesAsBlack { get; set; }
}
我首先通过设计器创建模型,然后生成我的数据库。以这种方式创建锦标赛可以正常工作,但由于某种原因,玩家创建会引发错误。 Id 的字段类型为Computed。
【问题讨论】:
-
由于您的
Id字段是计算出来的(可能是身份),因此您不应为其分配值。 -
由于某种原因,当我将我的字段设置为 Identity 时,值会自动生成,但是当我将我的字段设置为 Identity 时,该值将是必需的...
-
OK,将 Id 字段 StoreGeneratedPattern 设置为 none 解决了问题。
-
“需要的值”是什么意思?
-
是的,如果您需要自己设置
Id的值,则不应将Identity用于列,而应将StoreGeneratedPattern设置为none。
标签: c# .net entity-framework ado.net