如何搭建.NETEntityFramework分布式应用系统框架搭建

详细资料: /dingfangbo/p/5771741.html
学习 ASP.NET MVC 也有一段时间了,打算弄个小程序练练手,做为学习过程中的记录和分享。
首先,得确定需求,木有需求的话,那还搞个毛线呀!嗯&&大致思考了一下
OK!就这样,先从简单的开始(其实是复杂的不会做),后面有需要再添加(希望水平能达到)。功能确定了,那么改确定要做成什么样子的了。先和度娘商量一下先&&
终于在我的淫威之下,度娘交出了一个比较简洁的,源网站在(表示感谢),被小弟阉割了之后效果如下图:
接下来就开始编码了么?嗯!开始吧!打开心爱的VS2013,建立一个web项目,用 .net framework4.5.1 框架,这个是我能用的最新的了,为什么用最新的呢?因为&&喜欢,这就够了!(个人练习,用什么都无所谓啦!!!)。解决方案名称为 ShowPin 项目名称为 ShowPin.Web
再来一张,选择 MVC 模版,其他的没选过,不会用 =_=!! 身份验证用个人用户账户,这个是为了偷懒,话说 ASP.NET Identity 还是很给力的,不用白不用 ^_^~
点击确定之后,会看到以下界面:
解决方案结构:
先更新一把先:
好吧,开工吧!!在Models目录下建立博客分类(Category)和博客(Post)两个类,代码贴在下面
Category:
using System.Collections.G
using System.L
using System.W
namespace ShowPin.Web.Models
/// &summary&
/// &/summary&
public class Category
public Category()
this.Posts = new List&Post&();
/// &summary&
/// 获取或设置分类标题
/// &/summary&
public string Title {
/// &summary&
/// 该分类下的内容集合
/// &/summary&
public virtual ICollection&Post& Posts {
using System.Collections.G
using System.L
using System.W
namespace ShowPin.Web.Models
/// &summary&
/// &/summary&
public class Post
/// &summary&
/// 获取或设置内容标题
/// &/summary&
public string Title {
/// &summary&
/// 获取或设置内容
/// &/summary&
public string Content {
/// &summary&
/// 获取或设置内容发布日期
/// &/summary&
public DateTime CreateDate {
/// &summary&
/// 获取或设置点击数
/// &/summary&
public int hits {
/// &summary&
/// 获取或设置分类ID
/// &/summary&
public string CategoryId {
/// &summary&
/// 获取或设置分类
/// &/summary&
public virtual Category Category {
好了,接下来就是传说中的DBContext
ObjectContext:
using System.Collections.G
using System.Data.E
using System.L
using System.W
namespace ShowPin.Web.Models
/// &summary&
/// 数据上下文
/// &/summary&
public class ObjectContext : DbContext
public ObjectContext()
: base("ShowPinContext")
/// &summary&
/// 分类列表
/// &/summary&
public DbSet&Category& Categories {
/// &summary&
/// 博文列表
/// &/summary&
public DbSet&Post& Posts {
在 web.config 的 connectionStrings 节点添加如下代码:
&add name="ShowPinContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-ShowPin.CIntegrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-ShowPin.Context.mdf" providerName="System.Data.SqlClient" /&
大概是这个样子的,看下面的图片
好吧,接下来就让用数据库迁移功能,让代码在数据库中表现出来。
下面这个就是&程序包管理控制台&
输入:Enable-Migrations 然后按下&回车&键
这个&& 出错了,唉&&出师不利啊!!错误原因就是当前项目中存在两个上下文类型,SB VS 不知道要用哪个来生成数据库,所以&&
输入:Enable-Migrations -ContextTypeName ShowPin.Web.Models.ObjectContext 再&回车&
又出错了=_=!!
模型生成过程中检测到一个或多个验证错误:
ShowPin.Web.Models.Category: : EntityType&Category&未定义键。请为该 EntityType 定义键。
ShowPin.Web.Models.Post: : EntityType&Post&未定义键。请为该 EntityType 定义键。
Categories: EntityType: EntitySet&Categories&基于未定义任何键的类型&Category&。
Posts: EntityType: EntitySet&Posts&基于未定义任何键的类型&Post&。
这个是因为没有定义主键,简单来说就是传说中的ID&& 在实体类上加上主键
/// &summary&
/// &/summary&
public string Id {
string 类型的主键,还是比较少见的。
再来一次,输入:Enable-Migrations -ContextTypeName ShowPin.Web.Models.ObjectContext 再&回车&
我是猴子请来的逗逼么??
再来一次吧!!
输入:Enable-Migrations -ContextTypeName ShowPin.Web.Models.ObjectContext -force 再&回车&
搞定了 哈哈哈哈哈&&
他还生成了一些文件,来瞧瞧是什么东西。
多了一个 Migrations 目录,和 Configuration.cs 文件,这是个什么东西呢?先不管他。
接下来是对 Category 做 CRUD 操作,新建一个 Controller
点击确定之后,奇迹就出现了T T,在浏览器输入:http://localhost:10223/Category
地址是我的本地地址,请根据实际情况修改。
很遗憾,出错了!!!
因为之前启用数据库迁移之后,并没有让它更新,接下来就让它更新吧!!打开程序包管理器控制台,输入 Add-Migration ini &回车&
在 Migrations 目录下又多了个文件
是什么东西?先不管它,接着输入:Update-database
貌似成功了,看看 App_Data 目录
数据库生成好了,再刷新网页
终于成功了,哈哈&&接着是 Post
大功告成!
来个小小的总结:
1、上面出现的一些小问题,基本上是由于不细心造成的,所以在接下来的学习中一定要细心
2、关于&程序包管理器控制台&的知识在和
3、上面的编码模式为 &代码优先&、&代码先现行&,英文比较好记 code first
相关资料:
4、数据库迁移的相关资料:
接下来要做的事就是添加内容了,不用多久我就会升职加薪,当上总经理,出任CEO,赢取白富美,走上人生巅峰!想想还有点小激动~~
原文:/vin-c/p/3731068.html
阅读(...) 评论()asp.net 学习之路 项目整体框架简单的搭建
字体:[ ] 类型:转载 时间:
最近刚学了些关于asp.net mvc方面的知识,于是了要拿个小项目来练练手,提高下自己的code能力跟思维能力
最近刚学了些关于asp.net mvc方面的知识,于是了要拿个小项目来练练手,提高下自己的code能力跟思维能力.在此之前做东西都很简单,直接用动软那一套生成代码,生成一个简单的三层架构作为项目整体的框架,数据库访问层用的是ado.net.这么做了感觉挺麻烦,如果要项目要换数据库,要给数据库增加表或者给表增加某个字段,或者不使用ado.net用个orm框架来访问数据库等等,这样整体项目该动起来就提别的麻烦,为了解决这一些问题我们需要重新思考怎么搭建. 关于数据库访问层 数据库访问驱动层--大家都知道EF,NH跟Ado.net或者你自己实现的,这些都是为我们访问数据库或对数据库操作建立了桥梁,当然数据库也可能是不同的数据库,这些都是根据项目需求来定的,至于选择哪个则要视情况而定了.这里我就用了EF--model-first.我是直接在edmx里面设计模型,然后生成实体跟数据库,具体如下,做了个简单的权限管理(还没完全实现)..
代码如下: public class BaseRepository&T&:IDAL.IBaseRepository&T& where T:class { private DbContext container = EFContentFactory.GetCurrentContext(); #region 增加 public T AddEntity(T entity) { container.Set&T&().Add(entity);
} #endregion #region 删除 public bool DeleteEntity(T entity) { container.Set&T&().Attach(entity); container.Entry(entity).State = EntityState.D
} #endregion #region 修改 public bool UpdateEntity(T entity) { container.Set&T&().Attach(entity); container.Entry(entity).State = EntityState.M
} #endregion #region 查询 public IQueryable&T& GetEntities(Func&T, bool& lambdaWhere) { IQueryable&T& entities = container.Set&T&().Where(lambdaWhere).AsQueryable();
} #endregion #region 分页 public IQueryable&T& GetEntitiesByPageIndex&TS&(int pageIndex, int pageSize, out int totalCount, Func&T, bool& lambdaWhere, Func&T, TS& orderByRole, bool descending) { var temp = container.Set&T&().Where(lambdaWhere).AsQueryable(); totalCount = temp.Count(); if (descending) { temp = temp.OrderByDescending(orderByRole) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize).AsQueryable(); } else { temp = temp.OrderBy(orderByRole) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize).AsQueryable(); }
} #endregion }
到这一步我以为自己的数据库访问层写完了,然后可以去写业务逻辑层的东西了,实则不然,想想看,如果你要换数据库,或者换成ef或者ado.net 如果按老一套,则整个项目的每一个层都需要去替换,大大的增加了工作量,这里我们可以做个手脚,把数据访问层再给它抽象出一层来,这就需要用到接口了. IDAL.IBaseRepository&T&大体想想看我们的bll层如果没有接口我们直接这么写 dal.xxrepository=new xxrepository();老一套的写法,则跟我前面说的一样,可维护性替换性大大降低..我们现在可以这么写 IDAL.xxrepository=new xxrepository().这样我们替换DAL层时候 BLL层根部不需要关心你到底是怎么实现的.这一点非常的重要.接口就相当于一个契约,约束了你必须实现哪些功能,我们如果要增加功能可直接在接口中增添,接口需要为部分接口,如我给出的上面代码一样,基类需要一个接口,子类也需要.这样我们就抽象出一个数据库接口层. 抽象工厂与简单工厂 我们还可以对业务层跟数据库访问层再读的抽象出来,这里我们就需要用到工厂--其实很简单,从工厂类里面取出来的dal层的类并返回IDAL的接口
代码如下: public static class ShopDaoFactory { public static IUserInfoRepository UserInfoRepository { get{return new UserInfoRepository();} } public static IRoleRepository RoleRepository { get{return new RoleRepository();} } }
那么业务层拿到接口时也不需要关心到底怎么实现的,这样又是一层的抽象,当然你也可以用抽象工厂,利用反射跟配置外加缓存来实现,不过一般情况下简单工厂足够了,这里就相当于一个数据库访问层的入口了. 业务逻辑层的基类与子类  当我们实体模型多了的时候我们如果没有基类,则要写一堆重复性的东西,我们现在就要把这些重复的性的东西放到基类里面给我们实现,如同Dal层,我们定义了一个基类,但是在BLL层我们会遇到一个问题,IDAL.IBaseRepository&T&怎么获取从工厂获得接口了......思考一下.....我们的子类可以知道自己所需要的接口------我们可以做个手脚,让父类为抽象类,定义一个抽象方法,然后让子类重写改方法,并且在构造函数里面调用,因为我们必须用到这个接口,所以必须在构造函数里面
代码如下: public abstract class BaseService&T& :IBLL.IBaseService&T& where T:class, new () { public BaseService() { GetInstance(); } protected IDAL.IDbSession _DbSession = DbSeesionFactory.GetSession(); protected IDAL.IBaseRepository&T& CurrentRepository { } public abstract void GetInstance(); public IQueryable&T& GetEntities(Func&T, bool& lambdaWhere) { //_DbSession.SavaChanges(); return CurrentRepository.GetEntities(lambdaWhere); } public bool DeleteEntity(T entity) { CurrentRepository.DeleteEntity(entity); return _DbSession.SaveChanges() & 0; } public bool UpdateEntity(T entity) { CurrentRepository.UpdateEntity(entity); return _DbSession.SaveChanges() & 0; } public T AddEntity(T entity) { var en = CurrentRepository.AddEntity(entity); _DbSession.SaveChanges();
} public IQueryable&T& GetEntitiesByPageIndex&TS&(int pageIndex, int pageSize, out int totalCount, Func&T, bool& lambdaWhere, Func&T, TS& orderByRole, bool descending) { return CurrentRepository.GetEntitiesByPageIndex(pageIndex, pageSize, out totalCount, lambdaWhere, orderByRole, descending); } } }
其他的业务层也需要接口抽象出一层出来来作为约束,这样ui层也不需要关心你业务层怎么实现... 另外一种实现数据库入口的方试DBSession 我们先看一个类,dbsession里面有属性,为接口,对应的该接口所对应的实现类,两个方法SaveChanges(),与exesql(EF用的5.0+),里面返回的是当前EF线程类上下文的savechange()与执行sql语句的放回值,怎么才能确保当前进程内EF上下文只有一个了,我们看另外一个类.
代码如下: public partial class DbSession:IDAL.IDbSession { #region 代码生成器生成 //public IDAL.IRoleRepository RoleRepository //{ // get { return new RoleRepository();} //} //public IDAL.IUserInfoRepository UserInfoRepository //{ // get { return new UserInfoRepository();} //} #endregion public int SaveChanges() { return EFContentFactory.GetCurrentContext().SaveChanges(); } public int ExcuteSql(string strSql, System.Data.Objects.ObjectParameter[] parameters) { return EFContentFactory.GetCurrentContext().Database.ExecuteSqlCommand(strSql, parameters); } } public class EFContentFactory { public static DbContext GetCurrentContext() { DbContext obj = CallContext.GetData("DbContext") as DbC if (obj==null) { obj = new Model.DataContainer(); CallContext.SetData("DbContext",obj); }
CallContext 是类似于方法调用的线程本地存储区的专用集合对象,并提供对每个逻辑执行线程都唯一的数据槽。数据槽不在其他逻辑线程上的调用上下文之间共享,这是从msdn上截取的一段话,它有几个方法,这里面我们用到setdata跟getdata,来确保上下文线程内唯一,同样的我们让他接口化,与工厂内实现下--
代码如下: public class DbSeesionFactory { /// &summary& /// 保证线程内dbsession唯一 /// &/summary& /// &returns&&/returns& public static IDAL.IDbSession GetSession() { IDAL.IDbSession _dbSession = CallContext.GetData("DbSession") as IDbS if (_dbSession == null) { _dbSession = new DbSession(); CallContext.SetData("DbSession", _dbSession); } return _dbS } }
业务层的子类重写方法时这么来实现,同样基类加个: protected IDAL.IDbSession _DbSession = DbSeesionFactory.GetSession();
代码如下: public partial class ActionInfoService:BaseService&ActionInfo&,IBLL.IActionInfoService { public override void GetInstance() { CurrentRepository = _DbSession.ActionInfoR } } public partial class R_UserInfo_ActionInfoService:BaseService&R_UserInfo_ActionInfo&,IBLL.IR_UserInfo_ActionInfoService { public override void GetInstance() { CurrentRepository = _DbSession.R_UserInfo_ActionInfoR } } public partial class RoleService:BaseService&Role&,IBLL.IRoleService { public override void GetInstance() { CurrentRepository = _DbSession.RoleR } }
为什么要这么做了?当我们用EF的时候比如一个方法里面要操作多个表,就不断的需要用到上下文,这样可以帮我们剩不少事最后直接来个_dbsession.savechange().可以达到批量删除修改等等操作.具体看我,今天做了个批量删除的
代码如下: public int DeleteUsers(List&int& list) { foreach (var i in list) { _DbSession.UserInfoRepository.DeleteEntity(new UserInfo() {ID = i}); } return _DbSession.SaveChanges(); }
好困,把这几天学习的东西总结了下还是收获不少,虽然对里面有些东西不是非常的理解,慢慢看看就领悟了,分享给大学一同学习~
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具13055人阅读
.net技术文章(12)
实体对象通过远程序列化到客户端时,这些实体会与其数据上下文(也就是实体容器)分离,在客户端无法对实体直接进行查询以及操作,
Linq To SQL
1)附加对象(实体框架)
在实体框架的某个对象上下文内执行查询时,返回的对象会自动附加到该对象上下文。还可以将从源而不是从查询获得的对象附加到对象上下文。您可以附加以前分离的对象、由 NoTracking 查询返回的对象或从对象上下文的外部获取的对象。还可以附加存储在 ASP.NET 应用程序的视图状态中的对象或从远程方法调用或 Web 服务返回的对象。
使用下列方法之一将对象附加到对象上下文:
&调用 ObjectContext 上的 AddObject 将对象附加到对象上下文。当对象为数据源中尚不存在的新对象时采用此方法。
&调用 ObjectContext 上的 Attach 将对象附加到对象上下文。当对象已存在于数据源中但当前尚未附加到上下文时采用此方法。有关更多信息,请参见如何:附加相关对象(实体框架)。
&调用 ObjectContext 的 AttachTo,以将对象附加到对象上下文中的特定实体集。如果对象具有 null(在 Visual Basic 中为 Nothing)EntityKey 值,也可以执行此操作。
&调用 ObjectContext 上的 ApplyPropertyChanges。当对象已存在于数据源中,并且分离的对象具有您希望保存的属性更新时采用此方法。如果简单地附加该对象,则属性更改将丢失。有关更多信息,请参见如何:应用对已分离对象的更改(实体框架)。
应用对已分离对象的更改(实体框架)示例代码
&&&&&&&& &private static void ApplyItemUpdates(SalesOrderDetail updatedItem)
&&&&&&& &{
&&&&&&&&&&& // Define an ObjectStateEntry and EntityKey for the current object.
&&&&&&&&&&& EntityKey
&&&&&&&&&&& object originalI
&&&&&&&&&&& using (AdventureWorksEntities advWorksContext =
&&&&&&&&&&&&&&& new AdventureWorksEntities())
&&&&&&&&&&& {
&&&&&&&&&&&&&&& try
&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&& // Create the detached object's entity key.
&&&&&&&&&&&&&&&&&&& key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem);
&&&&&&&&&&&&&&&&&&& // Get the original item based on the entity key from the context
&&&&&&&&&&&&&&&&&&& // or from the database.
&&&&&&&&&&&&&&&&&&& if (advWorksContext.TryGetObjectByKey(key, out originalItem))
&&&&&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&&&&&& // Call the ApplyPropertyChanges method to apply changes
&&&&&&&&&&&&&&&&&&&&&&& // from the updated item to the original version.
&&&&&&&&&&&&&&&&&&&&&&& advWorksContext.ApplyPropertyChanges(
& &&&&&&&&&&&&&&&&&&&&&&&&&&key.EntitySetName, updatedItem);
&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&&&&&& advWorksContext.SaveChanges();
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& catch (InvalidOperationException ex)
&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&& Console.WriteLine(ex.ToString());
&&&&&&&&&&&&&&& }
&&&&&&&&&&& }
AddObject(string,object)
ApplyPropertyChanges(string,object)
DeleteObject(object)
using System.Collections.G
using System.T
namespace EFService
& public& interface IEntityHelper
&&&&& List&T& Query&T&(string filter,params object[] args);&&
&&&&& T Save&T&(T t);
&&&&& int Delete&T&(T t);&& &&&
using System.Collections.G
using System.T
using System.Data.O
using System.Data.Objects.DataC
using System.R
using System.L
using System.Linq.D
using System.Runtime.R
namespace EFService
&&& /// &summary&
&&& /// 为远程客户端提供实体查询和CUD操作的服务类
&&& /// &/summary&
&&& public class EntityHelper : MarshalByRefObject, IEntityHelper
&&&&&&& /// &summary&
&&&&&&& /// 在config文件中配置的数据上下文名称
&&&&&&& /// &/summary&
&&&&&&& string ContextN
&&&&&&& ServiceFactory factory = new ServiceFactory();
&&&&&&& public EntityHelper(string contextName)
&&&&&&&&&&& ContextName = contextN
&&&&&& &/// &summary&
&&&&&&& /// 创建数据上下文实例
&&&&&&& /// &/summary&&
&&&&&&& /// &returns&&/returns&
&&&&&&& public ObjectContext CreateObjectContext()
&&&&&&&&&&& string typeName = System.Configuration.ConfigurationManager.AppSettings[ContextName].ToString();
&&&&&&&&&&& return (ObjectContext)Activator.CreateInstance(Type.GetType(typeName));
&&&&&&& /// &summary&
&&&&&&& /// 查询操作
&&&&&&& /// &/summary&
&&&&&&& /// &typeparam name="T"&&/typeparam&
&&&&&&& /// &param name="filter"&查询条件组合&/param&
&&&&&&& /// &param name="args"&查询条件中的参数值&/param&
&&&&&&& /// &returns&返回实体集合&/returns&
&&&&&&& public List&T& Query&T&(string filter, params object[] args)
&&&&&&&&&&& using (ObjectContext context = CreateObjectContext())
&&&&&&&&&&& {
&&&&&&& &&&&&&&&return (context.GetType().InvokeMember(
&&&&&&&&&&&&&&&&&&& typeof(T).Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, context, null)
&&&&&&&&&&&&&&&&&&& as IQueryable&T&).Where(filter, args).ToList();
&&&&&&&&&& &}
&&&&&&& /// &summary&
&&&&&&& /// 保存实体
&&&&&&& /// &/summary&
&&&&&&& /// &typeparam name="T"&&/typeparam&
&&&&&&& /// &param name="t"&要添加或修改的实体&/param&
&&&&&&& /// &returns&返回添加或者更新后的实体&/returns&
&&&&&&& public T Save&T&(T t)
&&&&&&&&&&& EntityObject eo = t as EntityObject;
&&& &&&&&&&&using (ObjectContext context = CreateObjectContext())
&&&&&&&&&&& {
&&&&&&&&&&&&&&& if (eo.EntityKey == null)
&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&& context.AddObject(t.GetType().Name, t);
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& else
&&&&&&&&&&&&&&& {
&& &&&&&&&&&&&&&&&&&object target = ontext.GetObjectByKey(eo.EntityKey);&&&&&&&&&&&&&&&&&&& context.ApplyPropertyChanges(eo.EntityKey.EntitySetName, eo);
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& context.SaveChanges();
&&&&&&&&&&&&&&& return
&&&&&&&&&&& }
&&&&&&& /// &summary&
&&&&&&& /// 删除实体
&&&&&&& /// &/summary&
&&&&&&& /// &typeparam name="T"&&/typeparam&
&&&&&&& /// &param name="t"&&/param&
&&&&&&& /// &returns&成功删除的实体的数量&/returns&
&&&&&&& public int Delete&T&(T t)
&&&&&&&&&&& EntityObject eo = t as EntityObject;
&&&&&&&&&&& using (ObjectContext context = CreateObjectContext())
&&&&&&&&&&& {
&&&&&&&&&&&&&&& if (eo != null && eo.EntityKey != null)
&&&&&&&&&&&&&&&&&&& context.Attach(eo);
&&&&&&&&&&&&&&& context.DeleteObject(eo);
&&&&&&&&&&& &&&&return context.SaveChanges();
&&&&&&&&&&& }
using System.Collections.G
using System.L
using System.T
using System.Data.O
using System.C
namespace EFService
&&& /// &summary&
&&& /// 远程服务类工厂,负责创建服务对象
&&& /// &/summary&
&&& public class ServiceFactory : MarshalByRefObject
&&&&&&& /// &summary&
&&&&&&& /// 创建远程服务对象
&&&&&&& /// &/summary&
&&&&&&& /// &param name="connStringName"&数据上下文名称&/param&
&&&&&&& /// &returns&远程服务接口&/returns&
&&&&&&& public IEntityHelper CreateEntityHelper(string contextName)
&&&&&&&&&&& return new EntityHelper(contextName);
using System.Collections.G
using System.L
using System.T
using System.Runtime.R
using System.Runtime.Remoting.C
using System.Runtime.Remoting.Channels.T
namespace EFServiceHost
&&& class Program
&&&&&&& static void Main(string[] args)
&&&&&&&&&&& ChannelServices.RegisterChannel(new TcpChannel(9932),false);
&&&&&&&&&&& RemotingConfiguration.ApplicationName = "EFService";&&&&&&&&&&& RemotingConfiguration.RegisterActivatedServiceType(typeof(EFService.ServiceFactory));&&&&&&&&&&&
&&&&&&&&&&& Console.WriteLine("Start Server,Press any key to exit.");
&&&&&&&&&&& Console.ReadLine();
配置文件App.Config主要包括数据库连接信息以及自己定义一个数据上下文名称(这里和数据库连接名称相同,事实上不必相同),数据库连接信息可以从EFModel项目中配置文件中直接拷贝过来。内容如下:
&?xml version="1.0" encoding="utf-8"?&
&configuration&
& &connectionStrings&
&&& &add name="SchoolEntities" connectionString="metadata=res://*/EFModel.csdl|res://*/EFModel.ssdl|res://*/EFModel.provider=System.Data.SqlCprovider connection string=&Data Source=192.168.0.110/SQLEXPRESS;Initial Catalog=SIntegrated Security=TMultipleActiveResultSets=True&"& providerName="System.Data.EntityClient"& && &
&&& &/add&&
& &/connectionStrings&
& &appSettings &
&&& &add key="SchoolEntities"& value="EFModel.SchoolEntities, EFModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /&
& &/appSettings&
&/configuration&
编译成功后,拷贝EFModel和和EFService两个项目生成的dll文件至可执行文件EFServiceHost.exe同一目录下,点击运行EFServiceHost.exe。
static void Main()
&&&&&&&&&&& Application.EnableVisualStyles();
&&&&&&&&&&& Application.SetCompatibleTextRenderingDefault(false);
&&&&&&&&&&& //注册远程服务
&&&&&&&&&&& RemotingConfiguration.RegisterActivatedClientType(
&&&&&&&&&&&&&&& typeof(ServiceFactory), "tcp://localhost:9932/EFService");
&&&&&&&&&&& Application.Run(new Form1());
添加一个窗体Form1,放入一个按钮,在按钮点击处理事件里加入下面的代码,示范客户端如何调用远程服务类实现查询和CUD操作,简单起见,我不演示数据库的数据变化了,反正,看代码,你懂的。
private void button1_Click(object sender, EventArgs e)
&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&//通过远程服务工厂创建出远程服务对象,注意此处构造函数的参&
注意此处参&&&&&&&&&&&&&&&&&&&&&&&& // 数值为远程服务器上配置文件上的数据上下文名称
&&&&&&&&&&& ServiceFactory factory = new ServiceFactory();&&&&&&&&&
&&&&&&&&&& &&&&&&IEntityHelper entityHelper = factory.CreateEntityHelper("SchoolEntities");
&&&&&&&&&&& //查询实体
&&&&&&&&&&& List&Course& courses = entityHelper.Query&Course&("CourseID&@0",0);
&&&&&&&&&&& Course course = courses.SingleOrDefault(p =& p.CourseID == 1045);
&&&&&&&&&&&
&&&&&&&&&&& //修改实体
&&&&&&&&&&& course.Title = "update succeed";&&&&&&&&&&&
&&&&&&&&&&& entityHelper.Save(course);
&&&&&&&&&&&
&&&&&&&&&&& //删除实体
&&&&&&&&&&& entityHelper.Delete(course);
& &&&&&&&&&&//新增实体
&&&&&&&&&&& entityHelper.Save(new Course() { Title = "new course" });
&&&&&&&&&&&
EFServiceHost
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:48563次
排名:千里之外
原创:16篇
评论:17条
(1)(1)(1)(1)(1)(1)(1)(2)(1)(2)(7)

我要回帖

更多关于 系统框架搭建 的文章

 

随机推荐