參考
利用EF和C#泛型实现通用分页查询
Entity與DataTable互轉
Entity Framework 5 Updating a Record
回傳結果
public class Return_Msg
{
public bool Status;
public string Message;
public Return_Msg(bool status, string message)
{
Status = status;
Message = message;
}
}
1.新增
public Return_Msg InsertData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Add(entity);
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.InsertData<Sys_Menu>(menu);
2.修改
public Return_Msg UpdateData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Attach(entity);
var entry = context.Entry(entity);
context.Entry(entity).State = EntityState.Modified;
// other changed properties
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.UpdateData<Sys_Menu>(menu);
3.刪除
public Return_Msg DeleteData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Remove(entity);
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.DeleteData<Sys_Menu>(menu);
4.查詢
依條件查詢
public DataTable GetDataByWhere<T>(Expression<Func<T, bool>> predicate) where T : class
{
using (var context = new DbContext())
{
return EntityToDataTable<T>(context.Set<T>().Where<T>(predicate).AsEnumerable<T>());
}
}
用法:DataTable dt = dbService.GetDataByWhere<Sys_Menu>(p => p.MenuName.Contains(txtMenuName.Text));
單一Table全部資料
public DataTable GetDataAll<T>() where T : class
{
using (var context = new HDContext())
{
return EntityToDataTable<T>(context.Set<T>().AsEnumerable());
}
}
用法:DataTable dt = dbService.GetDataAll<Sys_Menu>();