WCF方法不返回EF的结果

时间:2015-11-07 14:03:51

标签: c# asp.net-mvc entity-framework wcf app-config

我的解决方案中有一个WCF项目和一个EF项目,我正在调用我的EF获取一个对象,但我得到了null。我不确定为什么因为我的SQL Server数据库中有数据,所以我使用数据库优先建模,如果这对线索有任何影响。

SQL Server管理工具中的每个表都包含数据,但是当我向GetUser方法添加断点并逐步执行它时,每个表对象的计数为0,并且在结束时我返回一个User对象,它是null

WCF方法

    public User GetUser(string username, string password)
    {
        User user = new User();
        try
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                throw new Exception("Invalid username and password");
            }
            var context = new InventoryManagerEntities();
            var userContext =
                (from usr in context.Users
                    where usr.usr_Username == username && user.usr_Password == password
                    select usr).FirstOrDefault();

        }
        catch (Exception)
        {
            throw;
        }
        return user;
    } 

WCF App.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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings><add name="InventoryManagerEntities" connectionString="metadata=res://*/InventoryManagerDBModels.csdl|res://*/InventoryManagerDBModels.ssdl|res://*/InventoryManagerDBModels.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=JUNIORLABOLD4A3\SQLEXPRESS;initial catalog=InventoryManager;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /><add name="InventoryManagerEntities1" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=JUNIORLABOLD4A3\SQLEXPRESS;initial catalog=InventoryManager;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="InventoryManager.Services.UserService">
        <endpoint address="" binding="basicHttpBinding" contract="InventoryManager.Services.IUserServices">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/InventoryManager.Services/UserService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="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>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

EF类库App.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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="InventoryManagerEntities" 
         connectionString="metadata=res://*/InventoryManagerDBModels.csdl|res://*/InventoryManagerDBModels.ssdl|res://*/InventoryManagerDBModels.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=JUNIORLABOLD4A3\SQLEXPRESS;initial catalog=InventoryManager;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

1 个答案:

答案 0 :(得分:0)

您的代码中有两个错误。永远不会分配变量user,而谓词user.usr_Password == password是错误的。

public User GetUser(string username, string password)
{
    User user = new User(); // <= user is only initialized
    try
    {
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
        {
            throw new Exception("Invalid username and password");
        }
        var context = new InventoryManagerEntities();
        var userContext = // <= should be "user", not "var userContext"
            (from usr in context.Users
                where usr.usr_Username == username 
                   && user.usr_Password == password // <= should be usr.usr_Password
                select usr).FirstOrDefault();

    }
    catch (Exception)
    {
        throw;
    }
    return user;
} 

所以,在消除所有噪音之后:

if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
    throw new Exception("Invalid username and password");
}
var context = new InventoryManagerEntities();
return (from usr in context.Users
        where usr.usr_Username == username 
           && usr.usr_Password == password
        select usr).FirstOrDefault();