1. 程式人生 > >.NET之EntityFramework框架運用

.NET之EntityFramework框架運用

實現類 引用 mar 空間 demo () style net 完成

1.創建EF模型庫

創建類庫--》添加新建項--》選擇ADO.NET實體數據模型--》選擇 來自數據庫的EF選擇器--》配置數據庫鏈接以及相應的數據庫--》看底部(將app.Config中鏈接設置另存為)默認值改成你需要空間名(DemoEntity)--》實體框架6.X--》選擇相應的表--》模型命名空間;改成你需要的空間名:(Demo.EntityModel),點擊完成

2.創建實現類庫

引用剛剛的EF實體庫

3.添加相應的NuGet包:搜索:EntityFramework

點擊安裝;

4.開始操作EF模型庫

using EntityModel;
using System;
using
System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Transactions; namespace EntityFrameworkDB { class DB { public static void Add() { using (var dbContext = new DemoEntity()) {
var awardPool = new GXL_AwardPool() { ShopId = 2 }; dbContext.GXL_AwardPool.Add(awardPool); dbContext.SaveChanges(); } } public static void Update() { using (var dbContext = new
DemoEntity()) { var awardPool = new GXL_AwardPool() { ID = 1, ShopId = 2 }; dbContext.GXL_AwardPool.Attach(awardPool); dbContext.Entry(awardPool).State = EntityState.Modified; dbContext.SaveChanges(); } } public static void Del() { using (var dbContext = new DemoEntity()) { var awardPool = new GXL_AwardPool() { ID = 1 }; dbContext.GXL_AwardPool.Attach(awardPool); dbContext.GXL_AwardPool.Remove(awardPool); dbContext.SaveChanges(); } } public static void GetModel() { using (var dbContext = new DemoEntity()) { //查詢單個實體 var awardPool = dbContext.GXL_AwardPool.FirstOrDefault(x => x.ID == 1); //查詢多個實體 var awardPoolList = dbContext.GXL_AwardPool.Where(x => x.ShopId == 1).ToList(); //通過sql語句查詢單個實體 //dbContext.Database.SqlQuery<ShopsMyDto>(sql).FirstOrDefault(); //通過sql語句查謁多個實體 //dbContext.GXL_AwardPool.Where(x => x.ShopId == 1).ToList(); } } /// <summary> /// 提交事務 /// </summary> public static void Tijiao() { using (var dbContext = new DemoEntity()) { using (var scope = new TransactionScope()) { try { var awardPool = new GXL_AwardPool() { ShopId = 2 }; dbContext.GXL_AwardPool.Add(awardPool); var awardPoolIn = new GXL_AwardPoolIn() { ID = 1, ShopId = 2 }; dbContext.GXL_AwardPoolIn.Attach(awardPoolIn); dbContext.Entry(awardPoolIn).State = EntityState.Modified; //進行事務提交 dbContext.SaveChanges(); scope.Complete(); } catch { } } } } } }

.NET之EntityFramework框架運用