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();
好。搞定。就这么简单。我也研究了半天,看了很多资料。就可以修改实体类看看数据库的变法吧。