利用EF 和WCF 建立一个REST JSON Service. 首先我们要下载一个Visual Studio 的Template 叫 “ADO.NET C# POCO Entity Generator With WCF Support”.

这个主要是用于生成WCF的Model Class. 因为默认的EF 的Template是没有[DataMember]和[DataContract]这个Annotation的。

建立一个Visual Studio 的project.建立一个Entity framework EDMX。这里面我们有一个Table,

上面已经说过,默认的EF 4.0下生成的template是没有[DataMember]和[DataContract]这个Annotation的,所以我们要用新的Template来生成Model class.

如果你打开Employee.cs的时候,你会发现class上面是没有[DataContract],属性是没有DataMember的。

首先,我们先删除自动生成的template和Model class

首先回到EDMX,右键Add Code Generation Item…

选择 EF 5.x DbContext Generator with WCF Support

当我们加完之后,再看我们的Employee.cs

这里面要说一下,因为JSON不支持序列化IsReference这个属性,所以如果你要输出JSON的话,就需要删除这个IsReference.如果你输出时xml的话,IsReference是没问题的。

所以我们要进到template文件,删除这个IsReference,这个就很简单了,走一个简单的查询就可以了。注意,在这个template中IsReference有两处,记得全删除就可以了

基本上,Entity Framework上JSON的问题已经完成了,下面就是写Service了,我们就写一个Service,GetEmployee(int employeID)

首先,我们创建一个EmployeeService.svc,

这里有一点注意,如果你用UriTemplate = “employee/{id}”的话,Employee GetEmployee(int id)这里,就必须是String id,否则的话他会抛异常

好了,最后就是web.config了

webconfig里面没有什么,只要注意加一个endpointBehavior <webHttp />,然后你的service endpoint 里面behaviorConfiguration = 这个endpointBehavior.

还有就是你的service endpoint的binding type 是 webHttpBinding.

最后记得加mexHttpBinding

全部的web.config在这里

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfRestServiceSample.EmployeeService" behaviorConfiguration="serviceBehav">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="restfulBehaviour"
contract="WcfRestServiceSample.IEmployeeService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="restfulBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="serviceBehav">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
<connectionStrings>
<add name="TechsharpSolutionEntities" connectionString="metadata=res://*/MyCompany.csdl|res://*/MyCompany.ssdl|res://*/MyCompany.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost\Sql2008R2;initial catalog=TechsharpSolution;persist security info=True;user id=sa;password=9ijn)OKM;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

执行的结果是

源代码链接

Entity Framework + WCF REST JSON Service的更多相关文章

  1. Entity Framework + WCF 远程调用出错

            在使用Entity Framework中使用WCF,在程序中调用服务一直报错,我一直以为是WCF的哪个地方的配置有问题,找来找去,一直没有解决.         最后在网上找到一篇文章 ...

  2. Entity framework在用于WCF时创建数据模型的问题

    众所周知,WCF的传输对象,在创建时需要在类名上标识[DataContract]以及在属性上标识[DataMember],当我们在使用Entity framework时(不考虑Code first的情 ...

  3. Entity Framework在WCF中序列化的问题

    问题描述 如果你在WCF中用Entity Framework来获取数据并返回实体对象,那么对下面的错误一定不陌生. 接收对 http://localhost:5115/ReService.svc 的 ...

  4. 精进不休 .NET 4.5 (12) - ADO.NET Entity Framework 6.0 新特性, WCF Data Services 5.6 新特性

    [索引页][源码下载] 精进不休 .NET 4.5 (12) - ADO.NET Entity Framework 6.0 新特性, WCF Data Services 5.6 新特性 作者:weba ...

  5. 如何使用ASP.NET Web API OData在Oracle中使用Entity Framework 6.x Code-First方式开发 OData V4 Service

    环境: Visual Studio 2013 + .Net Framework 4.5.2 1.新建项目 2.安装OData,ODP.NET 安装的包: 下面是部分代码: using System; ...

  6. JSON Support in PostgreSQL and Entity Framework

    JSON 和JSONB的区别(What's difference between JSON and JSONB data type in PosgresSQL?) When should be use ...

  7. Windows Service 项目中 Entity Framework 无法加载的问题

    Windows Service 项目引用了别的类库项目,别的项目用到了 Entity Framework(通过Nuget引入),但是我的 Windows Service 无法开启,于是我修改了 App ...

  8. Newtonsoft.Json高级用法,json序列号,model反序列化,支持序列化和反序列化DataTable,DataSet,Entity Framework和Entity,字符串

    原文地址:https://www.cnblogs.com/yanweidie/p/4605212.html 手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口 ...

  9. Entity Framework在WCF中序列化的问题(转)

    问题描述 如果你在WCF中用Entity Framework来获取数据并返回实体对象,那么对下面的错误一定不陌生. 接收对 http://localhost:5115/ReService.svc 的 ...

随机推荐

  1. Spring Data JPA教程, 第五部分: Querydsl(未翻译)

    The fourth part of my Spring Data JPA tutorialdescribed how you can implement more advanced queries ...

  2. 深度剖析WordPress主题结构(转)

    利用强大的技术,可以把基于wordpress的网站做成各种各样的形式,这除了要求wordpress主题开发人员精通html,PHP,JS,CSS等技术,还需要开发者掌握WordPress主题的框架. ...

  3. C# 调用第三方DLL完整实例

    C# 调用第三方DLL完整实例 分类: C/C++ 以下代码为本人在实际项目中编写的调用第三方DLL接口程序的完整代码. public class ExecuteDLL : Form { ...//忽 ...

  4. c语言向文件中写入

    创建一个文件使用fopen打开,然后使用fprintf输出,最后关闭文件流 FILE *out; out = fopen("test.txt","a+"); i ...

  5. HTML5画布Canvas

    一.Canvas概念介绍 1.概念 Canvas : 画布 2.作用 : HTML5 Canvas 元素用于图形的绘制, 通过脚本(通常是JavaScript)来完成.它本身只是个图形容器,必须使用脚 ...

  6. JS 的点点滴滴

    1. ||含义 : 返回第一个有效值 eg : <script type="text/javascript"> var a=""; var c = ...

  7. R语言聚类方法&主要软件包-K-means

    主要4中软件包 stas:主要包含基本统计函数. cluster:用于聚类分析. fpc:含聚类算法函数(固定聚类.线性回归聚类等). mclust:处理高斯分布混合模型,通过EM算法实现聚类.分类及 ...

  8. 常用小方法 or 语法

    --> 获取外部文件 def groovyUtils = new GroovyUtils( context ) def xmlFilePath = groovyUtils.getProjectP ...

  9. 汇编语言(学习笔记-----[bx]和loop)

    1.[bx]是什么??     和[0]有些类似,[0]表示内存单元,它的偏移地址是0      [bx]同样也表示一个内存单元,它的偏移地址在bx中,mov ax,[bx]  (字)   mov  ...

  10. 文件映射spring 使用classpath方式加载hibernate映射文件

    在改章节中,我们主要介绍文件映射的内容,自我感觉有个不错的建议和大家分享下 <!-- 批量指定到classpath下面 --> <property name="mappin ...