WCF实体框架无法访问实体子级

时间:2012-05-08 09:46:51

标签: wcf entity-framework children

我正在用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!");

        }

我尝试调试它,这个函数返回Customer和它 孩子BankAccounts,我也禁用了延迟加载。 我发现如果我注释掉这一行

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

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

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

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

和MyDbContext构造函数中的diable ProxyCreation。

this.Configuration.ProxyCreationEnabled = false;

1 个答案:

答案 0 :(得分:0)

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

dc.Customers.Include("BankAccounts")

无论如何,您的主要问题是循环引用(客户引用了帐户,帐户具有对客户的反向引用),这会破坏默认的WCF序列化。你必须inform serializer了解他们的存在。