zoukankan      html  css  js  c++  java
  • EF测试自动修改数据库结构

    1.配置类

    <connectionStrings>
    <add name="test1" connectionString="Data Source=.;Initial Catalog=test1;Integrated Security=true" providerName="System.Data.SqlClient" />
    </connectionStrings>

    internal sealed class Configuration<TContext> : DbMigrationsConfiguration<TContext> where TContext : DbContext
    {
    public Configuration()
    {
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(TContext context)
    {

    }
    }

     2.初始化类

    public SchoolContext() : base("name=test1")
    {
    }
    static SchoolContext()
    {
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolContext, Configuration<SchoolContext>>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
    }

    3.实体类

    public class Student
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    //public int Text { get; set; }
    public virtual Course Course { get; set; }
    }
    public class Course
    {
    public int StudentID { get; set; }
    public string Name { get; set; }
    [JsonIgnore]
    public virtual Student Student { get; set; }
    }

    4.映射类

    public class StudentMap : EntityTypeConfiguration<Student>
    {
    public StudentMap()
    {
    ToTable("Student");
    HasKey(d => d.ID);

    HasRequired(p => p.Course).WithRequiredPrincipal(p => p.Student);
    HasOptional(p => p.Course).WithRequired(p => p.Student);
    }
    }
    public class CourseMap : EntityTypeConfiguration<Course>
    {
    public CourseMap()
    {
    ToTable("Course");
    HasKey(p => p.StudentID);
    }
    }

    5.测试

    SchoolContext ctx = new SchoolContext();
    var s = new Student()
    {
    Name = "1",
    Age = 12,
    Course = new Course() { Name = "12" }
    };
    ctx.Set<Student>().Add(s);
    ctx.SaveChanges();

    var list = ctx.Set<Student>().ToList();
    var jsonString = JsonConvert.SerializeObject(list);
    Console.WriteLine(jsonString);
    Console.ReadLine();

    好。搞定。就这么简单。我也研究了半天,看了很多资料。就可以修改实体类看看数据库的变法吧。

  • 相关阅读:
    团队项目第二阶段冲刺第六天
    团队项目冲刺第二阶段第五天
    团队项目冲刺第二阶段第四天
    团队项目冲刺第二阶段第三天
    大道至简阅读笔记1
    团队项目冲刺第二阶段第二天
    团队项目第二阶段冲刺第一天
    团队项目冲刺第九天
    团队项目冲刺第八天
    团队项目冲刺第七天
  • 原文地址:https://www.cnblogs.com/Logan626/p/5644472.html
Copyright © 2011-2022 走看看