c#类生成表
第一步:
创建MyContext类
public class MyContext:DbContext
{
public MyContext():base()
{
}
public DbSet<User> User { get; set; }
public DbSet<Temp> Temp { get; set; }
public DbSet<Student> Student { get; set; }
public DbSet<StudentAddress> StudentAddress { get; set; }
public DbSet<Grade> Grade { get; set; }
public DbSet<Course> Course { get; set; }
}
User,Temp,Student,StudentAddress,Grade,Course是相应的类,里面自定义属性
eg:创建User类,表名为UserInfo 生成表为MyData.UserInfo
[Table("UserInfo", Schema = "MyData")]
public class User
{
[Key]//默认把Id或者classNameId作为主键。通过[key]可以指定主键,如果是数字类型,默认自增
public int Id { get; set; }
public string Account { get; set; }
public string PassWrod { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime? InsertTime { get; set; }
public bool enable { get; set; }
}
第二步:调用方法
using (MyContext context = new MyContext())
{
UserInfo user = new UserInfo();
context.UserInfo.Add(user);
TempInfo temp = new TempInfo();
context.TempInfo.Add(temp);
StudentInfo student = new StudentInfo();
context.StudentInfo.Add(student);
StudentAddressInfo stuAddress = new StudentAddressInfo();
context.StudentAddressInfo.Add(stuAddress);
GradeInfo grade = new GradeInfo();
context.GradeInfo.Add(grade);
CourseInfo course = new CourseInfo();
context.CourseInfo.Add(course);
context.SaveChanges();
}
表生成完成
生成表另外一种方法:用命令方式执行
打开程序包管理器控制台,执行以下命令生成表
1.Enable-Migrations -EnableAutomaticMigrations //开启迁移功能
2.Add-Migration 名称 //修改模型后,生成新的迁移文件
3.Update-Database -Verbose //将修改提交到数据库
每次在更新前需要把数据库中的表最好先删除一遍