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();

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

  • 相关阅读:
    Spring Cloud (八):服务调用追踪 sleuth & zipkin
    Spring Cloud (七):API 网关
    Spring Cloud (六):声明式 REST 请求 Feign
    maven 下载 jar 包到本地
    K8S 设置 Pod 使用 host 网络、配置 DNS
    Spring Cloud (五):容错处理 Hystrix
    Spring Cloud (四):客户端实现负载均衡
    [数仓]数据仓库设计方案
    [知识图谱]Neo4j知识图谱构建(neo4j-python-pandas-py2neo-v3)
    [Pandas]利用Pandas处理excel数据
  • 原文地址:https://www.cnblogs.com/Logan626/p/5644472.html
Copyright © 2011-2022 走看看