使用IList或ICollection作为DataMember时WCF服务出错

时间:2012-05-24 09:19:31

标签: wcf entity-framework

我正在开发一个使用Entity Framework代码第一种方法和MVC作为用户界面的示例系统。在这里,我使用WCF服务与用户界面和系统进行通信。当我在Employee实体中使用List或集合时,它给出了以下错误。我确定这是由于收藏。

“接收到http:/localhost/GreetingHost/EmployeeService.svc的HTTP响应时发生错误。这可能是由于服务端点绑定不使用HTTP协议。这也可能是由于HTTP请求上下文被服务器中止(可能是由于服务关闭)。有关详细信息,请参阅服务器日志。“

以下是问候项目中包含的实体和服务:

Employee.cs

[DataContract]
[KnownType(typeof(Greeting))]
public class Employee
{
    [Key()]
    [DataMember]
    public string UserId { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public int Age { get; set; }
    [DataMember]
    [ForeignKey("EmployeeUserID")]
    public virtual IList<Greeting> Greetings
    {
        get
        {
            if (this._greetings == null)
            {
                this._greetings = new List<Greeting>();
            }
            return _greetings;
        }
        set { _greetings = value; }
    }
    private IList<Greeting> _greetings;
}

Greeting.cs

[DataContract]
public class Greeting
{
    [Key()]
    [DataMember]
    public int GreetingID { get; set; }
    [DataMember]
    public string Salutation { get; set; }
    [DataMember]
    public string Message { get; set; }
    [DataMember]
    public DayStatusWrapper DayStatusWrapper { get; set; }
    [DataMember]
    public string EmployeeUserID { get; set; }
    [DataMember]
    public virtual Employee Employee { get; set; }
}

GreetingDBContext.cs

public class GreetingDBContext :DbContext 
{      
    public DbSet<Greeting> Greetings { get; set; }
    public DbSet<Employee> Employees { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Employee>().
                HasMany(d => d.Greetings).
                WithRequired(c => c.Employee).
                HasForeignKey(c => c.EmployeeUserID).WillCascadeOnDelete();
        modelBuilder.Entity<Employee>()
                .HasKey(c => c.UserId);
        modelBuilder.Entity<Greeting>()
                .HasKey(c => c.GreetingID);
    }
}

EmployeeServices.cs

public class EmployeeService
{
    private GreetingDBContext db = new GreetingDBContext();

    public void AddEmployee(string UserId, string Name, int Age)
    {
        Employee emp = new Employee();
        emp.UserId = UserId;
        emp.Name = Name;
        emp.Age = Age;
        db.Employees.Add(emp);
        db.SaveChanges();
    }

    public Employee getEmployee(string UserId)
    {
        Employee selectedEmployee = null;
        foreach (Employee item in db.Employees)
        {
            if (item.UserId == UserId)
            {
                selectedEmployee = item;
                break;
            }
        }
        return selectedEmployee;
    }

}

我使用WCF服务应用程序来托管服务。这里的代码来自 GreetingHost project.IEmployeeServices.cs

[ServiceContract]
public interface IEmployeeService
{
    [OperationContract]
    void AddEmployee(string UserId, string Name, int Age);

    [OperationContract]
    Employee getEmployee(string UserId);
}

EmployeeService.svc.cs

public class EmployeeService : IEmployeeService
{
    Greeting.EmployeeService serviceImplementation = new Greeting.EmployeeService();

    public void AddEmployee(string UserId, string Name, int Age)
    {
        serviceImplementation.AddEmployee(UserId,Name,Age);
    }

    public WcfGreating.Employee getEmployee(string UserId)
    {
        return serviceImplementation.getEmployee(UserId);
    }
}

服务主机成功:

在我的MVC应用程序中使用以上服务引用:

    EmployeeServiceClient employeeService = new EmployeeServiceClient();

    public ActionResult Profile(string id)
    {
        Employee emp = employeeService.getEmployee(id);

        return View(emp);
    }

从服务中收集员工时,返回了上述的CommunicationException。任何人都可以帮助我吗?

谢谢!

修改:

客户端的Web.config

<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="EmployeeService" closeTimeout="00:01:00" openTimeout="00:01:00"
          receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
          transactionFlow="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
          textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00"
            enabled="false" />
          <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
              algorithmSuite="Default" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost/GreetingHost/EmployeeService.svc"
        binding="wsHttpBinding" bindingConfiguration="EmployeeService"
        contract="EmployeeServiceReference.IEmployeeService" name="EmployeeService">
        <identity>
          <servicePrincipalName value="host/7TK3T3J.fareast.corp.microsoft.com" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>

服务的配置

<configuration>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="MyBehaviors" >
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
    <bindings>
        <wsHttpBinding>
            <binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
        </wsHttpBinding>
    </bindings>
    <services>
        <service name="GreetingHost.EmployeeService" behaviorConfiguration="MyBehaviors">
            <endpoint address="http://localhost/GreetingHost/EmployeeService.svc"
                binding="wsHttpBinding" bindingConfiguration="wsHttpBindingWithTXFlow"
                name="EmployeeService" contract="GreetingHost.IEmployeeService" />
          <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
        </service>
    </services>
</system.serviceModel>

2 个答案:

答案 0 :(得分:0)

你可以试试这个 -

simple product

很抱歉迟到的回复;)

答案 1 :(得分:0)

LazyLoading中停用DbContext