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.
Idfield is computed (probably Identity), you should not assign a value to it.Idyourself, you should not useIdentityfor the column and you should setStoreGeneratedPatterntonone.