Generic
Repository with Object Context
Generic
Class :
public class GenericRepository<T> : IDisposable where T : class
{
private XSharingEntities _ObjContext;
IObjectSet<T> objSet;
public
GenericRepository(XSharingEntities context)
{
_ObjContext = context;
objSet =
_ObjContext.CreateObjectSet<T>();
}
public void Insert(T entity)
{
if (entity != null)
{
objSet.Attach(entity);
objSet.AddObject(entity);
}
}
public void Delete(T entity)
{
if (entity != null)
{
objSet.DeleteObject(entity);
}
}
public T
getDetail(Expression<Func<T, bool>> where)
{
return
objSet.Where(where).FirstOrDefault();
}
public IEnumerable<T> GetList()
{
return objSet.ToList();
}
public IEnumerable<T> GetList(Expression<Func<T,bool>>
where)
{
return objSet.Where(where).ToList();
}
public void Save()
{
_ObjContext.SaveChanges();
}
public void Dispose()
{
_ObjContext.Dispose();
GC.SuppressFinalize(this);
}
}
Use generic
class in our code
XSharingEntities objContext = new XSharingEntities();
public GenericRepository<SharingComment> objCFSCode
{
get
{
GenericRepository<SharingComment> obj =
new GenericRepository<SharingComment>(objContext);
return obj;
}
}
Do openrations in User Code
using (objCFSCode)
{
/// For Update
var cmnt = objCFSCode.getDetail(p => p.CommentPK == 60217);
cmnt.Comment = "for Now";
cmnt.CommentDate = DateTime.Now;
cmnt.NotificationFK = 14;
cmnt.UserFK = 1;
objCFSCode.Save();
// For
Insert
SharingCFSCode obj = new SharingCFSCode();
//
SharingCFSCode is table
obj.Application = "Test";
obj.CFSCode = "AAAAAA";
obj.CFSDescription = "This is Test CFS";
obj.CFSPK = 123458;
objCFSCode.Insert(cmnt);
objCFSCode.Save();
// for
Delete
objCFSCode.Delete(cmnt);
objCFSCode.Save();
}
No comments:
Post a Comment