1

I am trying to add a record into table using Entity Framework and I get DbUpdateException when I execute this method on _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;
}

My Player model looks like this:

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; }
}

I have created model via designer first and then generated my database. Tournament creation in this way works fine, but for some reason player creation throws an error. The type of field Id is Computed.

6
  • Since your Id field is computed (probably Identity), you should not assign a value to it. Commented Nov 29, 2015 at 21:16
  • For some reason, when I set my field to Identity the value would be generated automatically, but when I set my field to Identity, the value would be required... Commented Nov 29, 2015 at 21:18
  • OK, setting the Id field StoreGeneratedPattern to none solved the problem. Commented Nov 29, 2015 at 21:24
  • What do you mean by "the value would be required"? Commented Nov 29, 2015 at 21:24
  • Yes, If you need to set the value of Id yourself, you should not use Identity for the column and you should set StoreGeneratedPattern to none. Commented Nov 29, 2015 at 21:26

1 Answer 1

1

Since your Id field is Identity, you should not assign a value to it. SQL Server will assign a new Identity value to it.

Remove the line Id = fideNumber

Also If you need to set the value of Id yourself, you should not use Identity for the column and you should set StoreGeneratedPattern to none.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.