简体   繁体   English

WCF和EF - 如何强制主机使用自己的连接字符串

[英]WCF and EF - How to force host to use its own connection string

Please excuse this question from an extreme newbie. 请原谅这个极端新手的问题。 I couldn't find the answer anywhere else. 我无法在其他任何地方找到答案。

I am writing a solution using Entity Framework and WCF. 我正在使用Entity Framework和WCF编写解决方案。 I will be writing several different clients. 我将写几个不同的客户。 I have placed the database connection string in both the Entity Framework project's app.config and the WCF host's app.config file. 我已将数据库连接字符串放在Entity Framework项目的app.config和WCF主机的app.config文件中。

In the host class, I wrote a simple test service contract with one method that simply retrieves all the customers from the database (from EF), called GetAllCustomers(). 在宿主类中,我用一种方法编写了一个简单的测试服务契约,该方法只是从数据库(来自EF)检索所有客户,称为GetAllCustomers()。 I then wrote a simple console client app to call GetAllCustomers() of the host and write all the customers' first and last names to the console. 然后我编写了一个简单的控制台客户端应用程序来调用主机的GetAllCustomers()并将所有客户的名字和姓氏写入控制台。

When I tried running the client, I got an error that says, "No connection string named 'TRS11Entities' could be found in the application config file. 当我尝试运行客户端时,我收到一条错误消息,“在应用程序配置文件中找不到名为'TRS11Entities'的连接字符串。

If I copy the connection string to the client console app's app.config file, it works fine, but if I comment it out, it doesn't work again. 如果我将连接字符串复制到客户端控制台应用程序的app.config文件,它可以正常工作,但如果我将其注释掉,它将无法再次运行。

Since the WCF host is doing the talking to the database, not the client directly, I don't understand why the client would need a connection string. 由于WCF主机正在与数据库进行通信,而不是直接与客户端进行通信,因此我不明白为什么客户端需要连接字符串。 I can only guess that the connection string is being passed up the chain from the client to the WCF host to Entity Framework. 我只能猜测连接字符串是从客户端传递到WCF主机到实体框架的链。 How can I make the WCF host tell .NET, "The buck stops here! Use my app.config's connection string and stop bothering the client for this info!" 如何让WCF主机告诉.NET,“降压停在这里!使用我的app.config的连接字符串并停止打扰客户端获取此信息!”

If it matters, I'm using Visual Studio Pro 2012, with all projects written in C# and targeting the V4.5 .NET framework. 如果重要的话,我正在使用Visual Studio Pro 2012,所有项目都是用C#编写的,目标是V4.5 .NET框架。

From APP.CONFIG in the WCF service project: 来自WCF服务项目中的APP.CONFIG:

  <system.serviceModel>
    <services>
      <service name="OrsonServiceLibrary.Service1">
        <endpoint address="localhost" binding="basicHttpBinding" name="TRS11Entities"
          contract="OrsonServiceLibrary.IService1">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/OrsonServiceLibrary/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <connectionStrings>
    <add name="TRS11Entities" connectionString="metadata=res://*/TRS11Model.csdl|res://*/TRS11Model.ssdl|res://*/TRS11Model.msl;provider=FirebirdSql.Data.FirebirdClient;provider connection string='character set=NONE;data source=localhost;initial catalog=&quot;C:\Program Files (x86)\TRS11\Data\DATA1100.FDB&quot;;user id=sysdba;password=masterkey'" providerName="System.Data.EntityClient" />
  </connectionStrings>

From APP.CONFIG in the Entity Framework project: 来自Entity Framework项目中的APP.CONFIG:

  <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>
  <connectionStrings>
    <add name="TRS11Entities" connectionString="metadata=res://*/TRS11Model.csdl|res://*/TRS11Model.ssdl|res://*/TRS11Model.msl;provider=FirebirdSql.Data.FirebirdClient;provider connection string='initial catalog=&quot;C:\Program Files (x86)\TRS11\Data\DATA1100.FDB&quot;;user id=sysdba;password=masterkey;data source=localhost'" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

From APP.CONFIG in the console client app: 来自控制台客户端应用程序中的APP.CONFIG:

  <system.serviceModel>
    <client>
      <endpoint address="http://localhost:8000/Service1" contract="OrsonServiceLibrary.IService1" binding="basicHttpBinding" />
    </client>
  </system.serviceModel>

  <!--<connectionStrings>
    <add name="TRS11Entities" connectionString="metadata=res://*/TRS11Model.csdl|res://*/TRS11Model.ssdl|res://*/TRS11Model.msl;provider=FirebirdSql.Data.FirebirdClient;provider connection string='character set=NONE;data source=localhost;initial catalog=&quot;C:\Program Files (x86)\TRS11\Data\DATA1100.FDB&quot;;user id=sysdba;password=masterkey'" providerName="System.Data.EntityClient" />
  </connectionStrings>-->

Code for GetAllCustomers() function in the WCF Service project: WCF服务项目中的GetAllCustomers()函数代码:

public HashSet<CUSTOMER> GetAllCustomers()
{
    var db = new TRS11Entities();

    HashSet<CUSTOMER> TheCusts = new HashSet<CUSTOMER>();

    foreach (CUSTOMER c in db.CUSTOMERs)
    {
        TheCusts.Add(c);
    }

    return TheCusts;
}

Console client app code: Console客户端应用代码:

static void Main(string[] args)
{
    Console.WriteLine("Press Enter to begin.");
    Console.ReadLine();

    Service1 MyService = new Service1();

    HashSet<CUSTOMER> cl = MyService.GetAllCustomers();

    foreach (CUSTOMER c in cl)
    {
        Console.WriteLine(c.CUSTFNAME + " " + c.CUSTLNAME);
    }

    Console.WriteLine("Press Enter to exit.");
    Console.ReadLine();
}

Host application code: 主机应用代码:

class Program
{
    static void Main(string[] args)
    {
        ServiceHost hostA = null;

        try
        {
            hostA = new ServiceHost(typeof(Service1));
            hostA.Open();

            Console.WriteLine();
            Console.WriteLine("Host started.  Press Enter to terminate host.");
            Console.ReadLine();

        }
        finally
        {
            if (hostA.State == CommunicationState.Faulted)
                hostA.Abort();
            else
                hostA.Close();
        }
    }
}

Thanks, Joe 谢谢,乔

Something tells me, that you're actually creating an instance of the service in your client app instead of using a proxy/channel. 有人告诉我,你实际上是在客户端应用程序中创建服务实例,而不是使用代理/渠道。

What is the Service1 type in the client app code? 客户端应用程序代码中的Service1类型是什么? Is it OrsonServiceLibrary.Service1 ? 是OrsonServiceLibrary.Service1吗?

Service1 MyService = new Service1();

If so, just remove reference to the service project and Add Service Reference instead. 如果是这样,只需删除对服务项目的引用和添加服务引用 This will generate a proxy, which you can use for accessing your service. 这将生成一个代理,您可以使用它来访问您的服务。

The client app isn't passing the connection to your wcf service. 客户端应用程序未将连接传递给您的wcf服务。 My guess is that you are making an un-intentional call to your database in your client app. 我的猜测是你在客户端应用程序中对数据库进行了无意的调用。 That would explain the error and why it works when you add the connection string to your console app. 这可以解释错误以及将连接字符串添加到控制台应用程序时它的工作原理。

Hope that helps. 希望有所帮助。 Post some code and we may be able to help more. 发布一些代码,我们可以提供更多帮助。

Without code it makes answering your question much harder, However, I suspect your issue is you have your connection string in a library app config file. 没有代码,它会更难回答您的问题,但是,我怀疑您的问题是您在库应用程序配置文件中有连接字符串。 The distinction here is that when you run the program the settings are loaded from the executing assembly app config file. 这里的区别是,当您运行程序时,设置将从正在执行的程序集应用程序配置文件中加载。

Check that the settings are in the "MyApp. exe .config" file. 检查设置是否在“MyApp的。exe文件的.config”文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用MySQL EF 6连接字符串 - How to use MySQL EF 6 with connection string 如何使WCF设置用于EntityFramework的连接字符串 - How to make WCF set a connection string for use with EntityFramework 如何强制迁移使用客户端上下文的连接字符串触发了迁移 - How to force the migration to use connection string of the client context triggered the migration 如何强制Linq to Sql类使用文件中的连接字符串 - How Force Linq to Sql classes to use connection string from file 我的连接字符串在其自己生成的连接字符串上出错。 我该如何解决? - My connectionstring is erroring on its own generated connection string. how would i fix this? 在Web主机上定义一个连接字符串,类似于在本地计算机上的调试模式下的EF连接字符串 - Define a Connection String on Web Host similar to EF Connection String in Debug Mode on Local Machine 如何在运行时使用EF和Structuremap更改连接字符串? - How to change connection string at runtime with EF and Structuremap? 如何使用动态连接字符串对EF 6服务进行DI - How to DI an EF 6 Service with dynamic connection string 在WCF中强制使用HttpClient关闭连接 - Force connection to close with HttpClient in WCF 如何在连接字符串中为EF CodeFirst配置ProviderManifestToken - How to configure ProviderManifestToken for EF CodeFirst in a Connection String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM