efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Auto increment does not work in mysql

Open fcin opened this issue 9 years ago • 3 comments

Setting auto increment field in entity framework does not work with mysql. I found this issue when I was trying to save a basic model with two properties:

public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
}

When I wanted to save a new user to mysql database I got an exception

Field 'Id' doesn't have a default value

private TetrominoContext _dbContext;

public HomeController(TetrominoContext dbContext)
{
    _dbContext = dbContext;
}
public IActionResult Index()
{
    var user = new User {
        Name = "Whatever"
    };

    _dbContext.Users.Add(user);
    _dbContext.SaveChanges(); // Throws exception
}

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.d__62.MoveNext()

I tried different combinations of [DatabaseGenerated(DatabaseGeneratedOption.Identity)] and [Key], but with no luck.

These are all of 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>

And my migration:

    [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 Startup.cs:

public class Startup
    {

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            
            //services.AddEntityFrameworkMySql().AddDbContext<TetrominoContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));
            services.AddEntityFrameworkMySql().AddDbContext<TetrominoContext>(options => options.UseMySql(Configuration.GetConnectionString("LocalTestDbConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseMvcWithDefaultRoute();
        }
    }

fcin avatar Jun 27 '17 08:06 fcin

This is an issue with the MySQL provider. Their issue tracker is here: https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues

ajcvickers avatar Jun 27 '17 15:06 ajcvickers

Fixed in 2.0

yukozh avatar Jul 06 '17 01:07 yukozh

I checked my migrations. When was developing it in Development mode was using Sqlite, so added annotations for MySql also, but missed on some other columns, then created the database. This error came up, and have figured out that on some other Id columns I missed MySql annotations, then added for those also. Still was getting the same error, because after final fix have to drop the database and run again.

Now works fine!

faridhuseynov avatar Oct 14 '19 09:10 faridhuseynov