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