【问题标题】:Entity Framework - DbUpdateException when adding entity实体框架 - 添加实体时出现 DbUpdateException
【发布时间】: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


【解决方案1】:

由于您的 Id 字段是 Identity,因此您不应为其分配值。 SQL Server 将为其分配一个新的Identity 值。

删除Id = fideNumber这一行

另外如果你需要自己设置Id的值,你不应该使用Identity作为列,你应该将StoreGeneratedPattern设置为none。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多