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 = ;
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=&quot;data source=.\sqlxu;initial catalog=TestMembership;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 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();
} }
}

EF,ADO.NET Entity Data Model简要的笔记的更多相关文章

  1. 关于VS2010“ADO.NET Entity Data Model模板丢失或者添加失败问题

    我最近在安装vs2010后,添加ADO.NET Entity 实体时发现,我的新建项里面并没有这个实体模型,后来我就在博问里面发表了问题,请求大家帮忙解决,悲剧的是少有人回应啊,呵呵,不过我还是在网上 ...

  2. VS2010中没有ado.net entity data model实体数据模型这一选项-解决办法

    前提先安装VS2010 SP1包. 解决办法: 1.从VS2010的安装盘目录下面的WCU\EFTools找到ADONETEntityFrameworkTools_chs.msi和ADONETEnti ...

  3. Create Entity Data Model

    http://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspx 官 ...

  4. Entity Framework Tutorial Basics(5):Create Entity Data Model

    Create Entity Data Model: Here, we are going to create an Entity Data Model (EDM) for SchoolDB datab ...

  5. Entity Framework的核心 – EDM(Entity Data Model) 一

    http://blog.csdn.net/wangyongxia921/article/details/42061695 一.EnityFramework EnityFramework的全程是ADO. ...

  6. 如何得到EF(ADO.NET Entity Framework)查询生成的SQL? ToTraceString Database.Log

    ADO.NET Entity Framework ToTraceString  //输出单条查询 DbContext.Database.Log  //这里有详细的日志

  7. 创建实体数据模型【Create Entity Data Model】(EF基础系列5)

    现在我要来为上面一节末尾给出的数据库(SchoolDB)创建实体数据模型: SchoolDB数据库的脚本我已经写好了,如下: USE master GO IF EXISTS(SELECT * FROM ...

  8. EntityFramework 学习 一 创建实体数据模型 Create Entity Data Model

    1.用vs2012创建控制台程序 2.设置项目的.net 版本 3.创建Ado.net实体数据模型 3.打开实体数据模型向导Entity Framework有四种模型选择 来自数据库的EF设计器(Da ...

  9. ADO.NET-EF:ADO.NET Entity Framework 百科

    ylbtech-ADO.NET-EF:ADO.NET Entity Framework 百科 ADO.NET Entity Framework 是微软以 ADO.NET 为基础所发展出来的对象关系对应 ...

随机推荐

  1. Glibc 与 libc 的区别和联系

    转http://blog.163.com/dragon_sjl@126/blog/static/100473339201107101517380/ 1.gcc(gnu collect compiler ...

  2. [svn]svn conflict 冲突解决

    转自:http://www.gezila.com/tutorials/17290.html 目录: 1. 同一处修改文件冲突 1.1. 解决方式一 1.2. 解决方式二 1.3. 解决总结 2. 手动 ...

  3. MySQL类型转换

    mysql为我们提供了两个类型转换函数:CAST和CONVERT,现成的东西我们怎能放过? BINARY[(N)] CHAR[(N)] DATE DATETIME DECIMAL SIGNED [IN ...

  4. [DHTML]什么是DHTML?

    DHTML 将 HTML.JavaScript.DOM 以及 CSS 组合在一起,用于创造动态性更强的网页. DHTML 总结 DHTML 只是一个术语,它描述了 HTML.JavaScript.DO ...

  5. Report_客制化以PLSQL输出HTML标记实现WEB报表(案例)

    2014-05-31 Created By BaoXinjian

  6. android js调试

    http://blog.allenm.me/ 其他平台去这篇文章看 //js调试调试功能支持4.4版本以上的 if(Build.VERSION.SDK_INT >= Build.VERSION_ ...

  7. setInterval()和setTimeout()的区别

    一.setInterval()函数的语法结构: setInterval(code,interval) setInterval()函数可周期性执行一段代码,也就是说代码会被周期性不断的执行下去. 函数具 ...

  8. nbIoT基础概念

    1. 物理信道(L1与L2之间) 上行:PRACH.PUSCH 下行:PBCH.PDCCH.PDSCH 2.逻辑信道(L2与L3之间) CCCH.DCCH.DTCH 3.信令(L3与NAS层之间) D ...

  9. 20145305 《Java程序设计》第7周学习总结

    教材学习内容总结 1.只有Lambda表达式,参数的类型必须写出来,如果有目标类型,在编译程序可推断出类型的情况下,可以不写出 2.Lambda表达式本身是中性的,不代表任何类型的实例,可用来表示不同 ...

  10. Centos下搭建ftp服务器

    完全不用那么麻烦,直接可以用xshell中自带的传输文件功能,下载客户端xftp安装就行,不用配置,可以在windows系统向Linux系统的任何文件地方上传下载文件,简单方便,大大节约时间, vsf ...