Entity Framework + WCF REST JSON Service

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

1-29-2014 11-39-33 AM

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

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

 image

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

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

image

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

image

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

image

选择 EF 5.x DbContext Generator with WCF Support

SNAGHTML5212d6

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

image

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

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

image

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

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

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

image

image

好了,最后就是web.config了

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

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

最后记得加mexHttpBinding

image

全部的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=localhostSql2008R2;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>

执行的结果是

image

源代码链接

原文地址:https://www.cnblogs.com/ruijiang21/p/3536440.html