实体框架 - 添加实体时的DbUpdateException

时间:2015-11-29 21:11:46

标签: c# .net entity-framework ado.net

我正在尝试使用Entity Framework将记录添加到表中,当我在DbUpdateException上执行此方法时,我得到_entities.SaveChanges();

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

1 个答案:

答案 0 :(得分:1)

由于您的Id字段为std::vector<Tree>,因此您不应为其指定值。 SQL Server将为其分配新的LSystem值。

删除第Identity

此外,如果您需要自己设置Identity的值,则不应将Id = fideNumber用于该列,并且应将Id设置为Identity