Entity Framework - 添加实体时出现 DbUpdateException
Entity Framework - DbUpdateException when adding entity
我正在尝试使用 Entity Framework 将记录添加到 table 中,当我在 _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
,因此您不应为其赋值。 SQL 服务器将为其分配一个新的 Identity
值。
删除行Id = fideNumber
此外,如果您需要自己设置Id
的值,则不应使用Identity
作为列,而应将StoreGeneratedPattern
设置为none
。
我正在尝试使用 Entity Framework 将记录添加到 table 中,当我在 _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
,因此您不应为其赋值。 SQL 服务器将为其分配一个新的 Identity
值。
删除行Id = fideNumber
此外,如果您需要自己设置Id
的值,则不应使用Identity
作为列,而应将StoreGeneratedPattern
设置为none
。