【发布时间】:2012-05-08 09:46:50
【问题描述】:
我正在使用 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;
【问题讨论】:
-
提示:不要使用 if 语句抛出异常,只需使用“return customer.Single();”,它会为您抛出异常。当您期望完全匹配时,应使用 Single。
-
这是因为导航属性是虚拟的。见this answer。
标签: wcf entity-framework children