1. 新建一个项目,添加一个ADO.NET Entity Data Model的文件,此文件会生成所有的数据对象模型,如果是用vs2012生的话,在.Designer.cs里会出现“// Default code generation is disabled for model 'C:\Work\Project\20140303\Delete\Model1.edmx'.
// To enable default code generation, change the value of the 'Code Generation Strategy' designer
// property to an alternate value. This property is available in the Properties Window when the model is
// open in the designer.”,而且会生成一些类文件。这时可以这样做,删除edmx模型下所有.tt和.diagram文件(如果不删直接执行下一步的话会报错提示),打开.edmx设计器,空白地方右键属性,将Code Genaration的属性值 从 None改为Default,就OK了。
2. 新建IRepository文件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration.Provider; using System.Linq.Expressions; using System.Data.Common; using System.Reflection; namespace Entity { public interface IRepository<T> { void Add(T entity); void Update(int ID, T entity); void Delete(int ID); IQueryable<T> FindAll(); T GetSingle(int ID); int Save(); } public class Repository<T> : IRepository<T> where T : class { protected EntityContext Context { get; set; } /// <summary> /// /// </summary> protected string EntityName { get { return typeof(T).Name; } } /// <summary> /// ObjectQuery的名称 /// </summary> protected string EntitySetName { get; set; } /// <summary> /// 连接字符 /// </summary> protected string ConnectionString { get { return System.Configuration.ConfigurationManager.ConnectionStrings["EntityContext"].ConnectionString; } } public Repository() { Context = new EntityContext(); } public Repository(EntityContext context) { Context = context; } public virtual void Delete(int ID) { T entity = GetSingle(ID); Context.DeleteObject(entity); } public virtual T GetSingle(int ID) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda<Func<T, bool>> ( Expression.Equal( Expression.Property( itemParameter, "ID" //默认为ID,如果不是ID,需要获取每个实体的PrimaryKey的字段名称 ), Expression.Constant(ID) ), new[] { itemParameter } ); return FindAll().FirstOrDefault(whereExpression); } public virtual T GetSingle64(Int64 ID) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda<Func<T, bool>> ( Expression.Equal( Expression.Property( itemParameter, "ID" //默认为ID,如果不是ID,需要获取每个实体的PrimaryKey的字段名称 ), Expression.Constant(ID) ), new[] { itemParameter } ); return FindAll().First(whereExpression); } public virtual void Add(T entity) { Context.AddObject(EntitySetName, entity); } public virtual void Update(int ID, T entity) { T oringal = GetSingle(ID); oringal = entity; Context.ApplyPropertyChanges(EntitySetName, oringal); } public virtual IQueryable<T> FindAll() { return Context.CreateQuery<T>("[" + EntitySetName + "]"); } public virtual int Save() { return Context.SaveChanges(); } /// <summary> /// 执行存储过程 /// </summary> /// <param name="CommandText"></param> /// <param name="param"></param> protected virtual int ExecuteStoredProcedure(string CommandText, params System.Data.Common.DbParameter[] param) { DbCommand cmd = new System.Data.SqlClient.SqlCommand(); using (DbConnection conn = new System.Data.SqlClient.SqlConnection(ConnectionString)) { cmd.Connection = conn; cmd.CommandText = CommandText; cmd.CommandType = System.Data.CommandType.StoredProcedure; if (param != null) cmd.Parameters.AddRange(param); conn.Open(); int result = 0; try { result = cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception("执行存储过程出错," + ex.Message); } finally { conn.Close(); } return result; } } /// <summary> /// 执行存储过程返回泛型实体数据集 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="CommandText"></param> /// <param name="param"></param> /// <returns></returns> protected virtual List<TEntity> ExecuteCommand<TEntity>(string CommandText, params System.Data.Common.DbParameter[] param) { List<TEntity> list = new List<TEntity>(); DbCommand cmd = new System.Data.SqlClient.SqlCommand(); using (DbConnection conn = new System.Data.SqlClient.SqlConnection(ConnectionString)) { cmd.Connection = conn; cmd.CommandText = CommandText; cmd.CommandType = System.Data.CommandType.StoredProcedure; if (param != null) cmd.Parameters.AddRange(param); conn.Open(); try { using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { //创建实例 TEntity RowInstance = Activator.CreateInstance<TEntity>(); //反射获取实例的属性 foreach (PropertyInfo Property in typeof(TEntity).GetProperties()) { try { //根据实例名称获取数据 if (reader[Property.Name] != DBNull.Value) { //将DataReader读取出来的数据填充到对象实体的属性里 Property.SetValue(RowInstance, Convert.ChangeType(reader[Property.Name], Property.PropertyType), null); } } catch { break; } } //将数据实体对象add到泛型集合中 list.Add(RowInstance); } } } catch (Exception ex) { throw new Exception("返回泛型实体出错," + ex.Message); } finally { conn.Close(); } } return list; } } }
3. 新建类的处理文件,例如为”aspnet_Roles“新建一个处理类。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entity { public interface Iaspnet_RolesRepository : IRepository<aspnet_Roles> { List<aspnet_Roles> GetList(); } public class aspnet_RolesRepository : Repository<aspnet_Roles>, Iaspnet_RolesRepository { public aspnet_RolesRepository() { EntitySetName = "aspnet_Roles"; } public List<aspnet_Roles> GetList() { return FindAll().ToList(); } } }
4. view层的操作。
在Global.asax里添加如下代码,这里用到了依赖注入。
static IUnityContainer _Container; public static IUnityContainer Container { get { if (_Container == null) { _Container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)System.Configuration.ConfigurationManager.GetSection("unity"); section.Configure(_Container, "TEST"); } return _Container; ; } }
并在webconfig里添加配置节点:
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <containers> <container name="TEST"> <types> <type name="aspnet_Roles" type="Entity.Iaspnet_RolesRepository, Entity" mapTo="Entity.aspnet_RolesRepository,Entity" /> </types> </container> </containers> </unity> <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <connectionStrings> <add name="MyDomainContext" connectionString="Data Source=WINSERVER08XU\SQLXU;user id=sa;password=101;Initial Catalog=XU" providerName="System.Data.SqlClient"/> <add name="EntityContext" connectionString="metadata=res://*/Entitycontext.csdl|res://*/Entitycontext.ssdl|res://*/Entitycontext.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlxu;initial catalog=TestMembership;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> <system.web> <httpRuntime targetFramework="4.5" /> <compilation debug="true" targetFramework="4.5" /> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> </configuration>
这里新插入的是:
<configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <containers> <container name="TEST"> <types> <type name="aspnet_Roles" type="Entity.Iaspnet_RolesRepository, Entity" mapTo="Entity.aspnet_RolesRepository,Entity" /> </types> </container> </containers> </unity>
注意低配置,<configSections>紧跟在<configuration>后面,否则会出错。
5. 在Controller里调用。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Microsoft.Practices.Unity; using Entity; namespace _20140303.Controllers { public class HomeController : Controller { Iaspnet_RolesRepository aspnet_RolesRepository; public ActionResult Default() { aspnet_RolesRepository = MvcApplication.Container.Resolve<Iaspnet_RolesRepository>("aspnet_Roles"); List<aspnet_Roles> vaspnet_RolesList = aspnet_RolesRepository.GetList(); return View(); } } }