转载:https://blog.csdn.net/killcwd/article/details/52023226
1.建立好自己的实体类
2.配置一个继承DbContext 的上下文类
Context类(方法名字和类名相同):
public YPContext()
: base("name=xxxx")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.AutoDetectChangesEnabled = true;
}
/*"name=xxxx"是配置链接数据库的字符串一般找哦web.config文件加入:
<connectionStrings>
<add name="xxxx" connectionString="data source=数据库名;initial catalog=生成的数据库文件名字;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
*/
3.配置映射实体类的设置属性,继承EntityTypeConfiguration<T>的类(就是配置每个类字段的大小、是否允许空.....):
public class 实体类属性映射: YP_EntityConfigurationBase<类名>
{
public YP_EmployeeMapping()
{
this.Property(x => x.Address).HasMaxLength(50);//地址
this.Property(x => x.LoginId).HasMaxLength(20).IsRequired();
this.Property(x => x.LoginPwd).HasMaxLength(20).IsRequired();
this.Property(x => x.Sex).HasMaxLength(5);
this.HasRequired(x => x.Store);
this.Property(x => x.Tel).HasMaxLength(11);
// this.Property(x => x.Birthday).IsOptional();//出生 ?类型要设置吗
// this.Property(x => x.Email);//邮箱
// this.Property(x => x.EmployeeName).HasMaxLength(20);//姓名
// this.Ignore(x => x.EntityVersion); //版本
// this.Property(x => x.IsDeleted).HasDatabaseGeneratedOption(true).IsRequired(); //?HasDatabaseGeneratedOption 是否写在Base里面?
//this.Property(x => x.RoleLevel).IsRequired();//枚举?
//this.Property(x => x.StoreID).IsRequired();//这个值从哪里来?
// this.Property(x => x.CreatonTime).IsRequired(); //?是否写在Base里面
//this.HasRequired(x => x.Store).WithMany();//外键 此处表YP_Employee一定要有值,多个表表此表的值
//this.HasRequired(x => x.Store).WithOptional();//外键 此处表YP_Employee一定要有值,也就是Store表可有可无此表的值
//this.HasRequired(x => x.Store).WithRequiredDependent();//外键
//this.HasRequired(x => x.Store).WithRequiredPrincipal();//外键
}
}
4.在Context类中加入读取配置映射文件方法:
public DbSet<xxxx> xxxx{ get; set; } //要生成的数据库的类名
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new xxxxMapping());//实体类属性映射的类
//禁用一对一关联删除
modelBuilder.Conventions.Remove<OneToOneConstraintIntroductionConvention>();
// 禁用一对多级联删除
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// 禁用多对多级联删除
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
//禁用表名复数
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Database.SetInitializer<Context>(null);
base.OnModelCreating(modelBuilder);
}
5.弄好前面的设置就可以执行控台的命令了
5.1生成一个配置类命令:Enable-Migrations -EnableAutomaticMigrations
5.2生成一个数据库更新脚本文件:Add-Migration InitialCreate
5.3生成数据库文件的命令:Update-Database -Verbose
6.这样的话就可以将实体类转化成数据库文件了