好了,好了,話很少說,EF的思想啊介紹啊,請看上一篇:juejin.im/post/5d99d0…html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Class
{
public int Id { get; set; }
public string ClassName { get; set; }
public virtual ICollection<Student> Student { get; set; }//表明的意思是一個班級有不少個學生
}
}
複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Student
{
public int Id { get; set; }
public string StuName { get; set; }
public virtual Class Class { get; set; } //表示學生是班級的
}
}
複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace ConsoleApp1
{
public class DbTextContext:DbContext
{
public DbTextContext(): base("conStr")
{
}
public DbSet<Class> Classe { get; set; }
public DbSet<Student> Student { get; set; }
}
}
複製代碼
<connectionStrings>
<add name="conStr" connectionString="data source=.;initial catalog=數據庫名寫你要建立的;persist security info=True;user id=xx;password=xxxxxx;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (DbTextContext db = new DbTextContext())
{
//建立數據庫,沒有就建立
db.Database.CreateIfNotExists();
db.SaveChanges();
}
}
}
}
複製代碼
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //將映射成的表移除複數約定,不加s
}
複製代碼
一些關於上下文的配置:www.cnblogs.com/libingql/p/…數據庫