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 为基础所发展出来的对象关系对应 ...
随机推荐
- 黄聪:如何阻止iframe里引用的网页自动跳转
今天做了个网页,要在网页里设置一个iframe,然后套用其他的网站.使用http://luanqi-cat.blogbus.com 这个网址的时候,出现了莫名其妙的问题,我的网页居然会强制自动跳转到这 ...
- android fragment getActivity()为空的另一个可能
目前这个方法得到空指针一般来说是因为Activity被销毁导致无法获取,但是开发中又出了一个低级错误导致getActivity为空. 因为我在Fragment的构造函数中调用这个方法了..此时Acti ...
- (MVVM) button enable 时,UI没有被刷新。
if (!this.CanExecuteSubmitButton) { this.CanExecuteSubmitButton = true; CommandManager.InvalidateReq ...
- Linux命令(20)linux服务器之间复制文件和目录
linux的scp命令: scp就是secure copy的简写,用于在linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器. 有时我们需要获得远程服务器上 ...
- image和字节流之间的相互转换
//将图片转化为长二进制 public Byte[] SetImgToByte(string imgPath) { FileStream file = new FileStream(imgPath, ...
- Ubuntu 12.04.2搭建nfs服务器
1.安装nfs 服务器(192.168.0.1) apt-get install nfs-kernel-server 2.修改nfs配置文件: vim /etc/exports 在exports文件中 ...
- 使用BeanUtils操作Bean属性
package com.wzh.test.beanutils; import java.lang.reflect.InvocationTargetException; import java.text ...
- Windows 10 中 Eclipse中无法添加Courier New字体的解决方法!
1,打开"C:\Windows\Fonts\"文件夹. 2,鼠标右键"Courier New",随后点击"显示",这样你就可以在Eclips ...
- 在windows下使用linux命令
<转:http://www.cnblogs.com/adgnat/archive/2011/07/16/2108098.html> 使用过linxu的伙计估计都会喜欢上linux各种各样强 ...
- WebService中实现上传下载文件
不多说,直接看代码: /*上传文件的WebService*/ using System; using System.Collections; using System.Collections.Gene ...