=========Common.cs==============
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
namespace Utitls
{
public class Common
{
/// <summary>
/// 克隆对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T Clone<T>(T obj)
{
T tmp = Activator.CreateInstance<T>();
foreach (var pi in obj.GetType().GetProperties())
{
var val = pi.GetValue(obj, null);
if (pi.GetGetMethod() != null && pi.GetSetMethod() != null && val!= null)
tmp.GetType().GetProperty(pi.Name).SetValue(tmp, val, null);
}
foreach (var fi in obj.GetType().GetFields())
{
var val = fi.GetValue(obj);
if (val != null)
tmp.GetType().GetField(fi.Name).SetValue(tmp, val);
}
return tmp;
}
/// <summary>
/// 从读取器中读取对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="reader"></param>
/// <returns></returns>
public static T ReadReader<T>(SqlDataReader reader)
{
T tmp = Activator.CreateInstance<T>();
for (int i = 0;i<reader.FieldCount;i++)
{
var pi = tmp.GetType().GetProperty(reader.GetName(i));
if(pi != null && pi.GetSetMethod() != null && reader[pi.Name] != System.DBNull.Value)
pi.SetValue(tmp, reader[pi.Name], null);
}
return tmp;
}
private static System.Data.SqlClient.SqlConnection _sqlConn;
private const string connString = "Data Source=.;Initial Catalog=Test20151223;Integrated Security=True";
/// <summary>
/// 全局sql链接,已初始化
/// </summary>
public static System.Data.SqlClient.SqlConnection sqlConn
{
get
{
if (_sqlConn == null)
_sqlConn = new SqlConnection(connString);
if (_sqlConn.State == System.Data.ConnectionState.Closed)
_sqlConn.Open();
return _sqlConn;
}
}
public static Cache globalCache = Cache.GetSingleton();
}
}
==============Cache.cs==========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
namespace Utitls
{
public interface ICache
{
string KeyIndex { get; }
}
/// <summary>
/// 全局缓存类
/// </summary>
public class Cache : SingletonMode<Cache>
{
private static Dictionary<string, Dictionary<string, object>> dictGolbal = new Dictionary<string, Dictionary<string, object>>();
/// <summary>
/// 添加缓存对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public int Add<T>(T obj) where T : ICache
{
Dictionary<string, object> dict;
if (dictGolbal.ContainsKey(typeof(T).Name))
{
dict = dictGolbal[typeof(T).Name];
dict.Add(obj.KeyIndex, Common.Clone<T>(obj) as object);
}
else
{
dict = new Dictionary<string, object>();
dict.Add(obj.KeyIndex, Common.Clone<T>(obj) as object);
dictGolbal.Add(typeof(T).Name, dict);
}
return 1;
}
/// <summary>
/// 查询缓存中对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public int Query<T>(ref T obj) where T : ICache
{
if (dictGolbal.ContainsKey(typeof(T).Name))
{
var dict = dictGolbal[typeof(T).Name];
if (dict.ContainsKey(obj.KeyIndex))
{
obj = Common.Clone<T>((T)dict[obj.KeyIndex]);
return 1;
}
}
return 0;
}
/// <summary>
/// 更新缓存对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public int Update<T>(T obj) where T : ICache
{
if (dictGolbal.ContainsKey(typeof(T).Name))
{
var dict = dictGolbal[typeof(T).Name];
if (dict.ContainsKey(obj.KeyIndex))
{
dict[obj.KeyIndex] = Common.Clone<T>(obj) as object;
return 1;
}
}
return 0;
}
/// <summary>
/// 从缓存中删除对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public int Delete<T>(T obj) where T : ICache
{
if (dictGolbal.ContainsKey(typeof(T).Name))
{
var dict = dictGolbal[typeof(T).Name];
if (dict.ContainsKey(obj.KeyIndex))
{
dict.Remove(obj.KeyIndex);
return 1;
}
}
return 0;
}
/// <summary>
/// 通过sql初始化缓存列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
public void InitCache<T>(string sql) where T : ICache
{
SqlCommand cmd = new SqlCommand(sql, Common.sqlConn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
this.Add<T>(Common.ReadReader<T>(reader));
}
}
/// <summary>
/// 查询缓存内对象,请不要修改查询出的对象数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func"></param>
/// <returns></returns>
public List<T> QueryWhere<T>(Func<T, bool> func) where T : ICache
{
var list = new List<T>();
if (dictGolbal.ContainsKey(typeof(T).Name) == false)
return list;
foreach (var o in dictGolbal[typeof(T).Name].Values)
if (func((T)o) == true)
list.Add((T)o);
return list;
}
}
}
=======SingletonMode.cs===============
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Utitls
{
/// <summary>
/// 单列模式构造类
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMode<T>
{
private static T obj;
public static T GetSingleton()
{
if (obj == null)
{
lock (typeof(T))
{
if (obj == null)
obj = Activator.CreateInstance<T>();
}
}
return obj;
}
}
}
========EntityFramework.cs========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace Utitls
{
/// <summary>
/// 实体特性类型
/// </summary>
public enum EntityFrameworkDataType : int
{
/// <summary>
/// 主键,不实现自动增长可以有多个
/// </summary>
KEY = 1,
/// <summary>
/// 自动增长的主键,只能存在一个
/// </summary>
KEY_AUTOINCREAMENT = 2,
/// <summary>
/// 不能为空
/// </summary>
NOTNULL = 4,
/// <summary>
/// 默认键
/// </summary>
NORMAL = 8
}
/// <summary>
/// 实体特性
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class EntityFrameworkAttribute : Attribute
{
public EntityFrameworkDataType dataType;
public EntityFrameworkAttribute(EntityFrameworkDataType dataType)
{
this.dataType = dataType;
}
public EntityFrameworkAttribute()
{
this.dataType = EntityFrameworkDataType.NORMAL;
}
}
public class EntityFramework<TContain, TEntity> : SingletonMode<TContain> where TEntity : ICache
{
private Dictionary<string, object> dictKey = new Dictionary<string, object>();
private List<string> listNotNull = new List<string>();
private List<string> listElement = new List<string>();
private bool bKeyAutoIncreament = false;
private string sql = string.Empty;
private string tableName;
public EntityFramework()
{
foreach (var pi in typeof(TEntity).GetProperties())
{
int itmp = pi.GetCustomAttributes(false).Where<object>(attr =>
{
return attr is EntityFrameworkAttribute;
}).Count<object>();
if (itmp != 0)
listElement.Add(pi.Name);
itmp = pi.GetCustomAttributes(false).Where<object>(attr =>
{
return attr is EntityFrameworkAttribute
&& ((attr as EntityFrameworkAttribute).dataType == EntityFrameworkDataType.NOTNULL);
}).Count<object>();
if (itmp != 0)
listNotNull.Add(pi.Name);
itmp = pi.GetCustomAttributes(false).Where<object>(attr =>
{
return attr is EntityFrameworkAttribute
&& ((attr as EntityFrameworkAttribute).dataType == EntityFrameworkDataType.KEY_AUTOINCREAMENT);
}).Count<object>();
if (itmp != 0)
bKeyAutoIncreament = true;
}
tableName = typeof(TContain).Name;
}
private void GetKey(TEntity entity)
{
dictKey.Clear();
foreach (var pi in entity.GetType().GetProperties())
{
int itmp = pi.GetCustomAttributes(false).Where<object>(attr =>
{
return (attr is EntityFrameworkAttribute)
&& (((attr as EntityFrameworkAttribute).dataType == EntityFrameworkDataType.KEY)
|| ((attr as EntityFrameworkAttribute).dataType == EntityFrameworkDataType.KEY_AUTOINCREAMENT));
}).Count<object>();
if (itmp != 0)
dictKey.Add(pi.Name, pi.GetValue(entity, null));
}
}
private string GetWhere(TEntity entity)
{
string sWhere = " WHERE ";
foreach (KeyValuePair<string, object> keyval in dictKey)
sWhere += string.Format("{0} = '{1}' AND ", keyval.Key, keyval.Value.ToString().Replace("'", "\""));
return sWhere.Remove(sWhere.Length - 4);
}
private void ValidateInsert(TEntity entity)
{
GetKey(entity);
foreach (string key in listNotNull)
if (entity.GetType().GetProperty(key).GetValue(entity, null) == null
|| entity.GetType().GetProperty(key).GetValue(entity, null).ToString().Trim() == string.Empty)
throw new Exception(string.Format("{0}值设定不得为空", key));
if (bKeyAutoIncreament == false)
foreach (KeyValuePair<string, object> keyval in dictKey)
if (keyval.Value == null || keyval.ToString().Trim() == string.Empty)
throw new Exception(string.Format("主键{0}不得为空", keyval.Key));
}
private void Validate(TEntity entity)
{
GetKey(entity);
if (bKeyAutoIncreament == false)
foreach (KeyValuePair<string, object> keyval in dictKey)
if (keyval.Value == null || keyval.ToString().Trim() == string.Empty)
throw new Exception(string.Format("主键{0}不得为空", keyval.Key));
}
/// <summary>
/// 从数据库中查询记录
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Query( TEntity entity)
{
Validate(entity);
sql = string.Format("SELECT * FROM {0}", tableName);
sql += GetWhere(entity);
SqlCommand cmd = new SqlCommand(sql, Common.sqlConn);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string key in listElement)
entity.GetType().GetProperty(key).SetValue(entity, reader[key], null);
return 1;
}
return 0;
}
}
/// <summary>
/// 从数据库中插入记录
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Insert( TEntity entity)
{
ValidateInsert(entity);
sql = string.Format("INSERT INTO {0} (", tableName);
foreach (string key in listElement)
{
if (bKeyAutoIncreament == true && dictKey.ContainsKey(key))
continue;
sql += string.Format("{0},", key);
}
sql = sql.Remove(sql.Length - 1) + " ) VALUES (";
foreach (string key in listElement)
{
if (bKeyAutoIncreament == true && dictKey.ContainsKey(key))
continue;
sql += string.Format("'{0}',", entity.GetType().GetProperty(key).GetValue(entity, null));
}
sql = sql.Remove(sql.Length - 1) + ")";
if (bKeyAutoIncreament == true)
sql += "; SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, Common.sqlConn);
if (bKeyAutoIncreament == true)
{
var obj = cmd.ExecuteScalar();
entity.GetType().GetProperty(dictKey.Keys.Single<string>()).SetValue(entity, int.Parse(obj.ToString()), null);
return 1;
}
else
return cmd.ExecuteNonQuery();
}
/// <summary>
/// 更新数据库记录
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Update( TEntity entity)
{
Validate(entity);
sql = string.Format("UPDATE {0} SET ", tableName);
foreach (string key in listElement)
{
if (dictKey.ContainsKey(key))
continue;
sql += string.Format(" {0} = '{1}',", key, entity.GetType().GetProperty(key).GetValue(entity, null));
}
sql = sql.Remove(sql.Length - 1);
sql += GetWhere(entity);
SqlCommand cmd = new SqlCommand(sql, Common.sqlConn);
return cmd.ExecuteNonQuery();
}
/// <summary>
/// 从数据库中删除记录
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Delete( TEntity entity)
{
Validate(entity);
sql = string.Format("DELETE FROM {0} ", tableName);
sql += GetWhere(entity);
SqlCommand cmd = new SqlCommand(sql, Common.sqlConn);
return cmd.ExecuteNonQuery();
}
/// <summary>
/// 从条件中查询对象
/// </summary>
/// <param name="Where">从where开始的条件语句</param>
/// <returns></returns>
public List<TEntity> QueryWhere( string Where)
{
if(Where.Trim().ToUpper().StartsWith("SELECT") == false)
sql = string.Format("SELECT * FROM {0} ", tableName);
sql += Where;
SqlCommand cmd = new SqlCommand(sql, Common.sqlConn);
var list = new List<TEntity>();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
list.Add(Common.ReadReader<TEntity>(reader));
}
return list;
}
/// <summary>
/// 先从缓存中读取,缓存中不存在再从数据库中读取
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Query2( ref TEntity entity)
{
int iret = Common.globalCache.Query<TEntity>(ref entity);
if (iret > 0)
return iret;
else
return Query(entity);
}
/// <summary>
/// 同时插入缓存和数据库
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Insert2( TEntity entity)
{
Insert(entity);
return Common.globalCache.Add<TEntity>(entity);
}
/// <summary>
/// 同时更新缓存和数据库
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Update2( TEntity entity)
{
Common.globalCache.Update<TEntity>(entity);
return Update(entity);
}
/// <summary>
/// 同时从缓存和数据库中删除
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Delete2( TEntity entity)
{
Common.globalCache.Delete<TEntity>(entity);
return Delete(entity);
}
}
}
======User实例==============
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Utitls;
using System.Web.Security;
namespace MvcApplication1.Models.Enitty
{
public class Users : EntityFramework<Users, Users.UserInfo>
{
public class UserInfo : ICache
{
[EntityFramework(EntityFrameworkDataType.KEY_AUTOINCREAMENT)]
public int ID { get; set; }
[EntityFramework(EntityFrameworkDataType.NOTNULL)]
public string Name { get; set; }
[EntityFramework(EntityFrameworkDataType.NOTNULL)]
public string Password { get; set; }
[EntityFramework()]
public string Email { get; set; }
[EntityFramework()]
public string LinkPhone { get; set; }
[EntityFramework(EntityFrameworkDataType.NOTNULL)]
public bool Enabled { get; set; }
[EntityFramework()]
public string Address { get; set; }
[EntityFramework()]
public string Mark { get; set; }
public string KeyIndex
{
get
{
return this.ID.ToString();
}
}
}
public string ValidateUser(UserInfo userInfo)
{
int iCount = Common.globalCache.QueryWhere<UserInfo>(o =>
o.Name == userInfo.Name.Trim()).Count();
if (iCount == 0)
return "当前用户不存在";
iCount = Common.globalCache.QueryWhere<UserInfo>(o =>
o.Name == userInfo.Name.Trim() && o.Password == userInfo.Password.Trim()).Count();
if (iCount == 0)
return "密码不正确";
return string.Empty;
}
public string RegisterUser(UserInfo userInfo)
{
try
{
if (userInfo.Name.Trim().Length < 2)
throw new Exception("名称长度不得小于2");
if (userInfo.Password.Trim().Length < 6)
throw new Exception("密码长度不得小于6");
if (Common.globalCache.QueryWhere<UserInfo>(o =>
o.Name.Trim() == userInfo.Name.Trim()).Count > 0)
throw new Exception("该用户名已注册!");
Insert2(userInfo);
return string.Empty;
}
catch (Exception e)
{
return e.Message;
}
}
public UserInfo GetUserByName(string Name)
{
return Common.globalCache.QueryWhere<UserInfo>(o => o.Name.Trim() == Name.Trim()).SingleOrDefault();
}
public void LogonOn(UserInfo userInfo)
{
var ticket = new FormsAuthenticationTicket(1, userInfo.Name, DateTime.Now, DateTime.Now.AddMinutes(10), true, "");
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public UserInfo GetCurrentUser()
{
var cookie = HttpContext.Current.Request[FormsAuthentication.FormsCookieName];
var ticket = FormsAuthentication.Decrypt(cookie);
if (ticket == null)
return null;
return Common.globalCache.QueryWhere<UserInfo>(o => o.Name.Trim() == ticket.Name.Trim()).SingleOrDefault();
}
public void LogonOff()
{
if (HttpContext.Current.Request.IsAuthenticated)
FormsAuthentication.SignOut();
}
public bool IsLogon
{
get
{
return HttpContext.Current.Request.IsAuthenticated;
}
}
}
}