I use entity framework core and mysql database.
My model looks like this:
public class User
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
When I try to add a user I get Field 'Id' doesn't have a default value
var user = new User {
Name = "Whatever"
};
_dbContext.Users.Add(user);
_dbContext.SaveChanges(); // Throws exception
And when I debug it I can see that my user's id value is -2147482647
InnerException {MySql.Data.MySqlClient.MySqlException: Field 'Id' doesn't have a default value
at MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet)
at MySql.Data.MySqlClient.MySqlDataReader.<ReadFirstResultSetAsync>d__62.MoveNext()
I tried using [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
and [Key]
, but it didn't do anything.
My generated migration looks like this:
[DbContext(typeof(TetrominoContext))]
[Migration("20170625090637_SixthMigration")]
partial class SixthMigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2");
modelBuilder.Entity("Tetromino.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.HasKey("Id");
b.ToTable("Users");
});
}
}
My packages:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.NodeServices" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="1.1.2" />
</ItemGroup>
After looking at my database it looks like entity framework doesn't set field Id
as auto-incremental, but I can't find a way to force it.
I recreated my database to see if it would help, but the error still occurs, so I suspect that I have to modify migration somehow.
Thanks to people at pomelo's github I was able to solve the problem. It turns out that I had to remove all of my previous migrations. For those who have the same problem.
Update-Database 0
(you have to go back
to first migration to be able to remove previous one's)Remove-Migration
Add-Migration migrationName
Update-Database
Also you don't need [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
nor [Key]
.