DAL 数据访问 EF firstcode
//SCHGNContextRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.SqlClient;
namespace SCHGN.DAL
{
public class SCHGNContextRepository<T>:IRepository<T> where T :class
{
protected DbSet<T> _objectSet;
protected SCHGNContext _context;
public SCHGNContextRepository(SCHGNContext context)
{
_objectSet = context.Set<T>();
_context = context;
}
public SCHGNContextRepository()
{
_context = new SCHGNContext();
_objectSet = _context.Set<T>();
}
public IQueryable<T> AsQueryable()
{
return _objectSet;
}
public IEnumerable<T> GetAll()
{
return _objectSet.ToList();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
return _objectSet.Where(where);
}
public T Single(Expression<Func<T, bool>> where)
{
return _objectSet.Single(where);
}
public T First(Expression<Func<T, bool>> where)
{
return _objectSet.First(where);
}
public void Delete(T entity)
{
if (_context.Entry(entity).State == System.Data.EntityState.Detached)
_objectSet.Attach(entity);
_objectSet.Remove(entity);
}
public void Add(T entity)
{
_objectSet.Add(entity);
}
public void Update(T entity)
{
_objectSet.Attach(entity);
_context.Entry(entity).State = System.Data.EntityState.Modified;
}
public void Dispose()
{
System.Diagnostics.Trace.WriteLine("context dispose");
_context.Dispose();
}
}
}
//IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace SCHGN.DAL
{
class IRepository<T>:IDisposable where T:class
{
IQueryable<T> AsQueryable();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> where);
T Single(Expression<Func<T, bool>> where);
T First(Expression<Func<T, bool>> where);
void Delete(T entity);
void Add(T entity);
void Update(T entity);
}
}

浙公网安备 33010602011771号