EF 的 CURD 操作

时间:2024-07-08 16:06:44

EF 的 CURD 操作

  这里采用了数据库 Northwind,下载地址:https://northwinddatabase.codeplex.com/

         /// <summary>
/// 添加
/// </summary>
/// <returns></returns>
public static int Add()
{
using (var db = new NorthwindEntities())
{
var customer = new Customers()
{
CustomerID = "fanguza",
Address = "地球",
City = "广东",
Phone = "",
CompanyName = "博客园",
ContactName = "反骨仔"
}; //方法一
//db.Customers.Add(customer); //方法二
var entry = db.Entry(customer);
entry.State = EntityState.Added; return db.SaveChanges();
}
}

         /// <summary>
/// 删除
/// </summary>
/// <returns></returns>
static int Delete()
{
using (var db = new NorthwindEntities())
{
var customer = new Customers()
{
CustomerID = "fanguzi"
}; db.Customers.Attach(customer);
db.Customers.Remove(customer); return db.SaveChanges();
}
}

         /// <summary>
/// 编辑(修改)
/// </summary>
/// <returns></returns>
static int Edit()
{
using (var db = new NorthwindEntities())
{
var customer = db.Customers.FirstOrDefault(u => u.CustomerID == "fanguzai"); if (customer == null)
{
return ;
} customer.ContactName = "erwuzai";
return db.SaveChanges();
}
}

         /// <summary>
/// 查询
/// </summary>
static Customers Query()
{
using (var db = new NorthwindEntities())
{
var query =
db.Customers.Where(u => u.ContactName == "fanguza").OrderBy(u => u.ContactName).Take(); return query.FirstOrDefault();
}
}

分页

         public IQueryable<Customers> GetPageOfCustomerses<TKey>(int pageIndex, int pageSize,
Expression<Func<Customers, bool>> wherExpression,
Expression<Func<Customers, TKey>> orderByExpression)
{
using (var db = new NorthwindEntities())
{
//分页前需要排序
return db.Customers.Where(wherExpression).OrderBy(orderByExpression).Skip((pageIndex - ) * pageSize).Take(pageSize);
}
}

批量增加

         static void BatchAdd()
{
using (var db = new NorthwindEntities())
{
for (var i = ; i < ; i++)
{
var customer = new Customers()
{
CustomerID = "fanguzai" + i,
Address = "中国",
City = "广州",
Phone = "" + i,
CompanyName = "阳春一中",
ContactName = "反骨仔" + i
}; db.Customers.Add(customer);
} db.SaveChanges();
}
}

其它

         public IQueryable<Customers> GetCustomerses<TKey>(Expression<Func<Customers, bool>> whereExpression,
Expression<Func<Customers, TKey>> orderExpression)
{
using (var db = new NorthwindEntities())
{
return db.Customers.Where(whereExpression).OrderBy(orderExpression);
}
}