Entity Framework + WCF REST JSON Service

利用EF 和WCF 創建一個REST JSON Service. 首先咱們要下載一個Visual Studio 的Template 叫 「ADO.NET C# POCO Entity Generator With WCF Support」.git

1-29-2014 11-39-33 AM

這個主要是用於生成WCF的Model Class. 由於默認的EF 的Template是沒有[DataMember]和[DataContract]這個Annotation的。github

創建一個Visual Studio 的project.創建一個Entity framework EDMX。這裏面咱們有一個Table,web

 image

上面已經說過,默認的EF 4.0下生成的template是沒有[DataMember]和[DataContract]這個Annotation的,因此咱們要用新的Template來生成Model class.restful

若是你打開Employee.cs的時候,你會發現class上面是沒有[DataContract],屬性是沒有DataMember的。app

image

首先,咱們先刪除自動生成的template和Model classide

image

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

image

選擇 EF 5.x DbContext Generator with WCF Supportspa

SNAGHTML5212d6

當咱們加完以後,再看咱們的Employee.csdebug

image

這裏面要說一下,由於JSON不支持序列化IsReference這個屬性,因此若是你要輸出JSON的話,就須要刪除這個IsReference.若是你輸出時xml的話,IsReference是沒問題的。3d

因此咱們要進到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=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>

執行的結果是

image

源代碼連接

相關文章
相關標籤/搜索