首页 > 代码库 > Entity Framework公共的增删改方法
Entity Framework公共的增删改方法
using System;using System.Collections.Generic;using System.Data.Entity;using System.Data.Entity.Infrastructure;namespace My{ /// <summary> Entity Framework公共的增删改方法。返回的是受影响的行数 </summary> public class PublicStore { //新增 public static int InsertObject(object obj) { Type t = obj.GetType(); int effect = -1; using (MyContext con = new MyContext()) { DbSet set = con.Set(t); set.Add(obj); effect = con.SaveChanges(); return effect; } } //批量新增 public static int InsertObjects(IEnumerable<object> objs) { int effect = 0; var et = objs.GetEnumerator(); if (et.MoveNext()) { Type t = et.Current.GetType(); using (MyContext con = new MyContext()) { DbSet set = con.Set(t); foreach (var o in objs) { set.Add(o); } effect = con.SaveChanges(); } } return effect; } //修改 public static int ModifyObject(object obj) { int effect = -1; using (MyContext con = new MyContext()) { DbEntityEntry entry = con.Entry(obj); entry.State = System.Data.EntityState.Modified; effect = con.SaveChanges(); return effect; } } //批量修改 public static int ModifyObjects(IEnumerable<object> objs) { int effect = 0; var et = objs.GetEnumerator(); if (et.MoveNext()) { Type t = et.Current.GetType(); using (MyContext con = new MyContext()) { foreach (var o in objs) { DbEntityEntry entry = con.Entry(o); entry.State = System.Data.EntityState.Modified; } effect = con.SaveChanges(); } } return effect; } //删除 public static int DeleteObject(object obj) { int effect = -1; using (MyContext con = new MyContext()) { DbEntityEntry entry = con.Entry(obj); entry.State = System.Data.EntityState.Deleted; effect = con.SaveChanges(); return effect; } } //批量删除 public static int DeleteObjects(IEnumerable<object> objs) { int effect = 0; var et = objs.GetEnumerator(); if (et.MoveNext()) { Type t = et.Current.GetType(); using (MyContext con = new MyContext()) { foreach (var o in objs) { DbEntityEntry entry = con.Entry(o); entry.State = System.Data.EntityState.Deleted; } effect = con.SaveChanges(); } } return effect; } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。