1

我正在用 EF 编写 WCF 服务。尝试返回客户实体的孩子时出现我的问题。下面的示例代码:

[DataContract]
public class Customer
{
        [Key]
        [DataMember]
        public int CustomerID { get; set; }

        [DataMember]
        public string FirstName { get; set; }

// Customer has a collection of BankAccounts
        [DataMember]
        public virtual ICollection<BankAccount> BankAccounts { get; set; }
}

[DataContract(IsReference = true)]
    public class BankAccount
    {
        [Key]
        [DataMember]
        public int BankAccountID { get; set; }

        [DataMember]
        public int Number { get; set; }

        // virtual property to access Customer
        //[ForeignKey("CustomerID")]
        [Required(ErrorMessage = "Please select Customer!")]
        [DataMember]
        public int CustomerID { get; set; }

        [DataMember]
        public virtual Customer Customer { get; set; }
    }

我得到的错误:

An error occurred while receiving the HTTP response to http://localhost:8732/Design_Time_Addresses/MyServiceLibrary/MyService/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

我调用的服务功能:

public Customer GetCustomer(int customerId)
        {
            var customer = from c in dc.Customers
                           where c.CustomerID == customerId
                           select c;
            if (customer != null)
                return customer.FirstOrDefault();
            else
                throw new Exception("Invalid ID!");

        }

我试图调试它,这个函数返回客户及其子银行帐户,我还禁用了延迟加载。我发现如果我注释掉这一行

public virtual ICollection<BankAccount> BankAccounts { get; set; } 

形成客户类,一切正常,除了我无法获得 BankAccount,它只返回客户。我是 WCF 的新手,所以请帮帮我。谢谢。

所以我找到了解决问题的方法。只需将来自 BankAccount 的客户参考标记为 IgnoreDataMember

[IgnoreDataMember]
public virtual Customer Customer { get; set; }

并在 MyDbContext 构造函数中禁用 ProxyCreation。

this.Configuration.ProxyCreationEnabled = false;
4

1 回答 1

0

您的函数需要启用延迟加载才能返回客户及其帐户,因为该函数不使用预加载。如果要禁用延迟加载,必须使用:

dc.Customers.Include("BankAccounts")

无论如何,您的主要问题是循环引用(客户对帐户有引用,而帐户对客户有反向引用),这会破坏默认的 WCF 序列化。您必须通知序列化程序它们的存在。

于 2012-05-08T10:17:39.177 回答