EF使用Code First修改生成数据库表名的方法
1、 重写OnModelCreating,去掉表名复数
System.Data.Entity.ModelConfiguration.Conventions;
public
class
MovieDBContext : DbContext
{
public
DbSet<Movie> Movies {
get
;
set
; }
protected
override
void
OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>().Property(p =>p.Price).HasPrecision(18, 2);
}
}
2、默认是model名,添加一个Attribute:System.ComponentModel.DataAnnotations; [Table("Product")] public class Product
EF初始化mysql数据库codefirst
1、添加引用EntityFramework、EntityFramework.SqlServer、MySql.Data、MySql.data.Entity.ef6
或者用NuGet安装EntityFramework、MySql.Data.Entity
2、在配置文件中加入
<configSections>
<!--For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468-->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider></providers>
</entityFramework>
<connectionStrings>
<add name="MySql" connectionString="Server=localhost; Database=wx.mms; Uid=root; Pwd=root; " providerName="MySql.Data.MySqlClient" />
</connectionStrings>
3、新建UserContext类,此类继承DbContext
public class UserDBContext:DbContext { public UserDBContext() : base("name=MySql") { } ////去掉表名复数 //protected override void OnModelCreating(DbModelBuilder modelbuilder) //{ // modelbuilder.Conventions.Remove<PluralizingTableNameConvention>(); //} public DbSet<model.user> User { get; set; } }
4、
//在没有数据库时创建一个,已存在,默认;如果pcontext.Patients.Add(p);添加一条,如果数据库已存在报错 Database.SetInitializer(new CreateDatabaseIfNotExists<UserDBContext>()); //在模型改变时,自动重新创建新的数据库,在开发过程中使用 //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<UserDBContext>()); //每次运行时,都重新生成数据库 //Database.SetInitializer(new DropCreateDatabaseAlways<UserDBContext>()); using (UserDBContext udb=new UserDBContext()) { //如果数据库已存在不加Database.SetInitializer(new CreateDatabaseIfNotExists<PatientContext>());,会报错 //udb.Database.Initialize(true); //直接添加一条数据,会生成数据库和数据, udb.Patients.Add(u); udb.SaveChanges(); }