您的位置:首页 > 数据库

EF框架--数据库增删改查泛型化

2016-07-18 00:00 316 查看
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
public class Tools
{
//添加实体
public static Boolean AddEntity<T>(T t) where T : class
{
using (var db = new MyContext())
{
//db.Entry(t).State = EntityState.Added;
db.Set<T>().Add(t);
if(db.SaveChanges()!=0)
return true;
}
return false;
}
//添加实体s
public static bool AddEntities<T>(IEnumerable<T> entities) where T:class
{
using (var db = new MyContext())
{
db.Set<T>().AddRange(entities);
if (db.SaveChanges() !=0)
{
return true;
}
}
return false;
}

//删除实体
public static bool RemoveEntity<T>(T t) where T : class
{
using (var db = new MyContext())
{
//db.Entry(t).State = EntityState.Deleted;
db.Set<T>().Remove(t);
if(db.SaveChanges()!=0)
return true;
}
return false;
}
//更新实体
public static bool UpdateEntity<T>(T t) where T : class
{
using (var db = new MyContext())
{
db.Entry(t).State = EntityState.Modified;
if(db.SaveChanges()!=0)
{
return true;
}
}
return false;
}
//查询 实体
public static T QueryEntity<T>( params object[] ob) where T : class
{
using (var db = new MyContext())
{
return db.Set<T>().Find(ob);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ef