EF,ADO.NET Entity Data Model简要的笔记
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="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();
} }
}
EF,ADO.NET Entity Data Model简要的笔记的更多相关文章
- 关于VS2010“ADO.NET Entity Data Model模板丢失或者添加失败问题
我最近在安装vs2010后,添加ADO.NET Entity 实体时发现,我的新建项里面并没有这个实体模型,后来我就在博问里面发表了问题,请求大家帮忙解决,悲剧的是少有人回应啊,呵呵,不过我还是在网上 ...
- VS2010中没有ado.net entity data model实体数据模型这一选项-解决办法
前提先安装VS2010 SP1包. 解决办法: 1.从VS2010的安装盘目录下面的WCU\EFTools找到ADONETEntityFrameworkTools_chs.msi和ADONETEnti ...
- Create Entity Data Model
http://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspx 官 ...
- 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 ...
- Entity Framework的核心 – EDM(Entity Data Model) 一
http://blog.csdn.net/wangyongxia921/article/details/42061695 一.EnityFramework EnityFramework的全程是ADO. ...
- 如何得到EF(ADO.NET Entity Framework)查询生成的SQL? ToTraceString Database.Log
ADO.NET Entity Framework ToTraceString //输出单条查询 DbContext.Database.Log //这里有详细的日志
- 创建实体数据模型【Create Entity Data Model】(EF基础系列5)
现在我要来为上面一节末尾给出的数据库(SchoolDB)创建实体数据模型: SchoolDB数据库的脚本我已经写好了,如下: USE master GO IF EXISTS(SELECT * FROM ...
- EntityFramework 学习 一 创建实体数据模型 Create Entity Data Model
1.用vs2012创建控制台程序 2.设置项目的.net 版本 3.创建Ado.net实体数据模型 3.打开实体数据模型向导Entity Framework有四种模型选择 来自数据库的EF设计器(Da ...
- ADO.NET-EF:ADO.NET Entity Framework 百科
ylbtech-ADO.NET-EF:ADO.NET Entity Framework 百科 ADO.NET Entity Framework 是微软以 ADO.NET 为基础所发展出来的对象关系对应 ...
随机推荐
- Python 模块学习:re模块
今天学习了Python中有关正则表达式的知识.关于正则表达式的语法,不作过多解释,网上有许多学习的资料.这里主要介绍Python中常用的正则表达式处理函数. 方法/属性 作用 match() 决定 R ...
- int long long范围
unsigned int 0-4294967295 int 2147483648-2147483647 unsigned long 0-4294967295long 2147483 ...
- MySQL处理数据库和表的常用命令
MySQL处理数据库和表的常用命令 [导读] 学习如何管理和导航MySQL数据库和表是要掌握的首要任务之一,下面的内容将主要对MySQL的数据库和表的一些常用命令进行总结,一些我们不得不掌握的命令,一 ...
- 如何用js来判断浏览器类型(ie,firefox)等等
现在网络上的浏览器,操作系统就象中国的方言一样,那个叫多啊!这给我们这些开发人员 带来了巨大的痛苦!虽然可能大家的喜好不同!用的系统也不同!有人喜欢用ie,有人喜欢用 firefox,还有人喜欢用腾讯 ...
- 更新nvm
在官方看到这个文档 ( cd "$NVM_DIR" git fetch origin git checkout `git describe --abbrev=0 --tags -- ...
- oracle新建数据库时怎么选择编码格式
源地址:https://zhidao.baidu.com/question/2009631596107727508.html 启动database configuration assistant,创建 ...
- C++学习16 继承时的名字遮蔽
如果派生类中的成员变量和基类中的成员变量重名,那么就会遮蔽从基类继承过来的成员变量.所谓遮蔽,就是使用新增的成员变量,而不使用继承来的. 成员函数也一样,如果函数名和参数签名都相同,就会造成遮蔽.如果 ...
- Js 时间与字符串转示例
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- spring获取bean的时候严格区分大小写
如题:spring获取bean的时候严格区分大小写 配置文件helloservice.xml中配置: <dubbo:reference id="IInsurance" int ...
- archlinux log 文件查看
# pacman -S gnome-system-log gnome-logsextra/gnome-logs 3.12.1-1 (gnome-extra) A log viewer for the ...