Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First MySql Pluralizing Tables

I am using the Microsoft Entity Framework with code first to manage my data (with MySQL). I have defined a POCO object, however, when I try to add data it says table Users doesn't exist. I looked in the DB and it created table User not Users. How can I remedy this? It is driving me nuts!

Thanks!

  public class User
 {
    [Key,Required]
    public int UserId { get; set; }

    [StringLength(20), Required]
    public string UserName { get; set; }

    [StringLength(30), Required]
    public string Password { get; set; }

    [StringLength(100), Required]
    public string EmailAddress { get; set; }

    [Required]
    public DateTime CreateDate { get; set; }

    [Required]
    public bool IsActive { get; set; }
}
like image 461
Jeffrey Kevin Pry Avatar asked Sep 26 '11 23:09

Jeffrey Kevin Pry


2 Answers

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace YourNamespace
{
    public class DataContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
        {
            dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public DbSet<User> User { get; set; }
    }
}
like image 158
Thulasiram Avatar answered Nov 15 '22 04:11

Thulasiram


I have not used MySQL with EF yet but regardless I think the solution is unbias. You need to turn off Pluralize Table Convention.

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;

public class MyDbContext: DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {    
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

Now EF will look for the literal of your object name to the table name.

Some great video tutorials are at http://msdn.microsoft.com/en-us/data/aa937723 under the Continue Learning Entity Framework. For additional learning experience, you can not specify the above but rather explicitly map the object 'user' to the table 'user'.

Additional References: http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx

like image 28
Jeff Willener Avatar answered Nov 15 '22 03:11

Jeff Willener