代码
/********************************************************************************************************************************
* Jin Tu
* 2010-11-16
*
* Entity inherited from this base class will implement functions:
* 1. use new keyword to create an instance, add it to database
* 2. get an entity from database, then delete it
* 3. get an entity from database, then update it
*
* Also, base class provides two static functions:
* 1. get all entities
* 2. get one entity with primary key field parameters
* 3. compare with lamdba expression to get entity list
*
*
* ***************************************************************************************************************************/
#define DEBUGGING
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Linq.Expressions;
namespace Tj.Linq
{
public class BaseEntity<TEntity, TContext>
where TEntity : class, new()
where TContext : DataContext, new()
{
static TContext _context = null;
Table<TEntity> _table = null;
static BaseEntity()
{
CreateContext();
}
static void CreateContext()
{
if(_context==null)
_context = Activator.CreateInstance<TContext>() as TContext;
}
void InitializeEntity()
{
_table = _context.GetTable<TEntity>();
}
public bool Add()
{
try
{
InitializeEntity();
_table.InsertOnSubmit(this as TEntity);
_context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
_context.SubmitChanges();
}
catch (System.Exception ex)
{
#if DEBUGGING
throw ex;
#else
return false;
#endif
}
return true;
}
public bool Update()
{
try
{
InitializeEntity();
_context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
_context.SubmitChanges();
}
catch (System.Exception ex)
{
#if DEBUGGING
throw ex;
#else
return false;
#endif
}
return true;
}
public bool Delete()
{
try
{
InitializeEntity();
_table.DeleteOnSubmit(this as TEntity);
_context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
_context.SubmitChanges();
}
catch (System.Exception ex)
{
#if DEBUGGING
throw ex;
#else
return false;
#endif
}
return true;
}
public static IList<TEntity> GetAll()
{
return _context.GetTable<TEntity>().Where(c=>c!=null).ToList();
}
/// <summary>
/// get one entity with primary key field parameters
/// </summary>
/// <param name="values">the values of each primary key field</param>
/// <returns>entity</returns>
public static TEntity GetByPk(object[] values)
{
Table<TEntity> table = _context.GetTable<TEntity>();
MetaTable metaTable = _context.Mapping.GetTable(typeof(TEntity));
List<MetaDataMember> pks = metaTable.RowType.DataMembers.Where(c => c.IsPrimaryKey).ToList();
if (pks == null)
throw new Exception("have no pk !");
string cond = null;
for (int i = 0; i < pks.Count(); i++)
{
cond += pks[i].MappedName + "==@" + i.ToString() + " and ";
}
cond = cond.Substring(0, cond.Length - 5);
// Expression parse;
ParameterExpression param = Expression.Parameter(typeof(TEntity), "c");// "c" indicates TEntity object
string[] conds=cond.Split(new string[1]{"and"},StringSplitOptions.RemoveEmptyEntries);
Expression left=null;
Expression right=null;
Expression body = null;
List<BinaryExpression> binExps = new List<BinaryExpression>();
for (int i = 0; i < conds.Length;i++ )
{
string fieldname="_"+conds[i].Split(new string[1]{"=="},StringSplitOptions.RemoveEmptyEntries)[0].Trim();
left = Expression.Field(param, typeof(TEntity).GetField(fieldname, BindingFlags.Instance | BindingFlags.NonPublic));
right = Expression.Constant(values[i]);
binExps.Add(Expression.Equal(left, right));//c.pk1=1
}
body = binExps[0];
for(int i=1; i<binExps.Count();i=i+2)
{
body = Expression.And(body, binExps[i]);//c=>c.pk1=1 and c.pk2="2" ....
}
LambdaExpression lamda = Expression.Lambda(body, param);
//search
TEntity[] entities = table.Where((Func<TEntity, bool>)lamda.Compile()).ToArray();
if (entities.Length == 1)
return entities[0];
return null;
}
public static IList<TEntity> GetByConditon(Expression<Func<TEntity, bool>> predicate)
{
Table<TEntity> table = _context.GetTable<TEntity>();
return table.Where(predicate).ToList();
}
}
}
* Jin Tu
* 2010-11-16
*
* Entity inherited from this base class will implement functions:
* 1. use new keyword to create an instance, add it to database
* 2. get an entity from database, then delete it
* 3. get an entity from database, then update it
*
* Also, base class provides two static functions:
* 1. get all entities
* 2. get one entity with primary key field parameters
* 3. compare with lamdba expression to get entity list
*
*
* ***************************************************************************************************************************/
#define DEBUGGING
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Linq.Expressions;
namespace Tj.Linq
{
public class BaseEntity<TEntity, TContext>
where TEntity : class, new()
where TContext : DataContext, new()
{
static TContext _context = null;
Table<TEntity> _table = null;
static BaseEntity()
{
CreateContext();
}
static void CreateContext()
{
if(_context==null)
_context = Activator.CreateInstance<TContext>() as TContext;
}
void InitializeEntity()
{
_table = _context.GetTable<TEntity>();
}
public bool Add()
{
try
{
InitializeEntity();
_table.InsertOnSubmit(this as TEntity);
_context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
_context.SubmitChanges();
}
catch (System.Exception ex)
{
#if DEBUGGING
throw ex;
#else
return false;
#endif
}
return true;
}
public bool Update()
{
try
{
InitializeEntity();
_context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
_context.SubmitChanges();
}
catch (System.Exception ex)
{
#if DEBUGGING
throw ex;
#else
return false;
#endif
}
return true;
}
public bool Delete()
{
try
{
InitializeEntity();
_table.DeleteOnSubmit(this as TEntity);
_context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
_context.SubmitChanges();
}
catch (System.Exception ex)
{
#if DEBUGGING
throw ex;
#else
return false;
#endif
}
return true;
}
public static IList<TEntity> GetAll()
{
return _context.GetTable<TEntity>().Where(c=>c!=null).ToList();
}
/// <summary>
/// get one entity with primary key field parameters
/// </summary>
/// <param name="values">the values of each primary key field</param>
/// <returns>entity</returns>
public static TEntity GetByPk(object[] values)
{
Table<TEntity> table = _context.GetTable<TEntity>();
MetaTable metaTable = _context.Mapping.GetTable(typeof(TEntity));
List<MetaDataMember> pks = metaTable.RowType.DataMembers.Where(c => c.IsPrimaryKey).ToList();
if (pks == null)
throw new Exception("have no pk !");
string cond = null;
for (int i = 0; i < pks.Count(); i++)
{
cond += pks[i].MappedName + "==@" + i.ToString() + " and ";
}
cond = cond.Substring(0, cond.Length - 5);
// Expression parse;
ParameterExpression param = Expression.Parameter(typeof(TEntity), "c");// "c" indicates TEntity object
string[] conds=cond.Split(new string[1]{"and"},StringSplitOptions.RemoveEmptyEntries);
Expression left=null;
Expression right=null;
Expression body = null;
List<BinaryExpression> binExps = new List<BinaryExpression>();
for (int i = 0; i < conds.Length;i++ )
{
string fieldname="_"+conds[i].Split(new string[1]{"=="},StringSplitOptions.RemoveEmptyEntries)[0].Trim();
left = Expression.Field(param, typeof(TEntity).GetField(fieldname, BindingFlags.Instance | BindingFlags.NonPublic));
right = Expression.Constant(values[i]);
binExps.Add(Expression.Equal(left, right));//c.pk1=1
}
body = binExps[0];
for(int i=1; i<binExps.Count();i=i+2)
{
body = Expression.And(body, binExps[i]);//c=>c.pk1=1 and c.pk2="2" ....
}
LambdaExpression lamda = Expression.Lambda(body, param);
//search
TEntity[] entities = table.Where((Func<TEntity, bool>)lamda.Compile()).ToArray();
if (entities.Length == 1)
return entities[0];
return null;
}
public static IList<TEntity> GetByConditon(Expression<Func<TEntity, bool>> predicate)
{
Table<TEntity> table = _context.GetTable<TEntity>();
return table.Where(predicate).ToList();
}
}
}
To use it, the next is examples:
1. dbml file
2.Use base class to Role entity class
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public partial class Role : Tj.Linq.BaseEntity<Role, DataClasses1DataContext>
{
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public partial class Role : Tj.Linq.BaseEntity<Role, DataClasses1DataContext>
{
}
}
3. entity use examples:
代码
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
////add
//Role role = new Role();
//role.Role_Name = "test";
//role.Add();
//get all
IList<Role> lstrole= Role.GetAll();
//get by primary key
Role role = Role.GetByPk(new object[2] { 3, "test" });
// role.Role_Name = "test555";
// role.Update(); //update
// role.Delete();//delete
//get by lamdba expression
IList<Role> lst = Role.GetByConditon(c => c.Role_ID == 3 && c.Role_Name =="test");
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
////add
//Role role = new Role();
//role.Role_Name = "test";
//role.Add();
//get all
IList<Role> lstrole= Role.GetAll();
//get by primary key
Role role = Role.GetByPk(new object[2] { 3, "test" });
// role.Role_Name = "test555";
// role.Update(); //update
// role.Delete();//delete
//get by lamdba expression
IList<Role> lst = Role.GetByConditon(c => c.Role_ID == 3 && c.Role_Name =="test");
}
}
}