EntityFramework是一種。net對象和數據庫對象關係映射程序(ORM)html
一.EF Core 和EF6sql
1.運行環境數據庫
(1)EF6:使用.netFramework包,只能運行在Windows平臺上ide
(2)EFCore:使用最新的EntityFramework Core包,支持跨平臺ui
2.功能比較spa
(1)EFCore中新增了一些新的功能,同時也缺乏一些EF6的功能.net
二.同時使用EF6和EFCorecode
1.經過命名空間別名指令輕鬆消除多義性htm
2.using Microsoft.EntityFrameworkCore; // use DbContext for EF Core 對象
3.using EF6 = System.Data.Entity; // use EF6.DbContext for the EF6 version
EF使用流程
1.建立項目引入EF6
2.建立XXXContext,繼承DBContext
public class SchoolContext : DbContext { public SchoolContext() : base("name=SchoolDBName")//配置文件中鏈接數據庫語句的Name { } public DbSet<SchoolInfo> SchoolInfo { get; set; } public DbSet<Student> Student { get; set; } }
3.建立實體模型
public class SchoolInfo { [Key] public Guid Guid { get; set; } public string SchoolName { get; set; } public string SchoolUrl { get; set; } public string Address { get; set; } public DateTime CreateSchool { get; set; } public string Phone { get; set; } public bool state { get; set; } } public class Student { [Key] public Guid Guid { get; set; } public string Name { get; set; } public Guid SchoolGuid { get; set; } public bool Sex { get; set; } }
4.設置鏈接的數據庫
<connectionStrings> <add name="SchoolDBName" connectionString="Data Source=.;database=SchoolDB;uid=sa;pwd=sasa;" providerName="System.Data.SqlClient" /> </connectionStrings>
5.填寫執行方法
static void Main(string[] args) { SchoolInfo schoolInfo = new SchoolInfo() { Guid = System.Guid.NewGuid(), SchoolName = "SchoolName", SchoolUrl = "SchoolUrl", Address = "Address", CreateSchool = DateTime.Now, Phone = "123456789", state = true, }; if (new SchoolInfoBLL().Add(schoolInfo)) { Console.WriteLine("成功"); } else { Console.WriteLine("失敗"); } Console.ReadKey(); }
若是類屬性發生變化
1.執行 enable-migrations -contexttypename SchoolContext
2.修改configuration.cs
internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApp4.Model.DataBase.SchoolContext> { public Configuration() { //開啓自動遷移 AutomaticMigrationsEnabled = true; ContextKey = "ConsoleApp4.Model.DataBase.SchoolContext"; } protected override void Seed(ConsoleApp4.Model.DataBase.SchoolContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. } }
3.執行add-migration InitialCreate
4.執行 update-database
注:以後的完屬性直接執行第4部便可
注意:當EF須要執行大批量數據時,能夠先生成完整的sql語句,而後直接執行sql語句
var sql = new StringBuilder(); for (int i = 0; i < 10000; i++) { //生成SQL sql.Append(ItemDetailBatchs.BatchAdd(entity)); } //一次性執行SQL db.Database.ExecuteSqlCommand(sql.ToString());
原文出處:https://www.cnblogs.com/JueXiaoQiang/p/10385152.html