【问题标题】:WCF Entity Framework can't access entity childrensWCF 实体框架无法访问实体子级
【发布时间】: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


【解决方案1】:

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

dc.Customers.Include("BankAccounts")

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

【讨论】:

  • 感谢您的回复,但我的问题仍然存在。
  • 您是否按照我在答案中提供的链接在哪里?
  • 是的,我做了,在那里我看到了你显示 EF4 实体无法序列化的图片,所以我检查了我的,我的看起来一样,所以我只是禁用了 ProxyCreation。我仍然没有完全理解 ProxyCreation 的作用,我对这一切还是陌生的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多