【问题标题】:Cyclic references using POCO entities and Silverlight services使用 POCO 实体和 Silverlight 服务的循环引用
【发布时间】:2012-02-29 16:48:20
【问题描述】:

我创建了几个 POCO 实体,它们之间存在关系。例如,“Individual”实体与“Collection”实体具有 OneToMany 关系。这是我定义它们的方式:

[DataContract(IsReference=true)]
[KnownType(typeof(User))]
[KnownType(typeof(Address))]
[KnownType(typeof(Collection))]
[KnownType(typeof(Donation))]
[KnownType(typeof(CollectorRating))]
[KnownType(typeof(DonatorRating))]
[Table("Individuals")]
public class Individual : User
{
    // ... Lots of attributes

    [DataMember]
    [InverseProperty("Collector")]
    public virtual ICollection<Collection> Collections { get; set; }

    // Lots of other attributes
}

还有集合实体:

[DataContract(IsReference=true)]
[KnownType(typeof(Individual))]
[KnownType(typeof(Organization))]
[KnownType(typeof(Donation))]
[KnownType(typeof(DeliveryDay))]
[KnownType(typeof(Address))]
[Table("Collections")]
public class Collection
{
    // Other attributes

    [DataMember]
    [InverseProperty("Collections")]
    public virtual Individual Collector { get; set; }

    // ... Attributes
}

我的服务是与 Silverlight 兼容的服务,它是这样定义的:

[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class IndividualService
{
    [OperationContract]
    public User GetByEmail(string email)
    {
        using (var context = new EntitiesContext())
        {
            Individual user = context.Individuals.SingleOrDefault(u => u.Email == email);

            return user;
        }
    }
}

这按预期工作:我收到一个单独的对象,该对象填充了数据成员和 null 集合数组。

但是,一旦我尝试包含这种关系:

context.Individuals.Include("Collections").SingleOrDefault(u => u.Email == email)

我有一个堆栈溢出异常,这很烦人。我很确定这是一个循环引用错误,但是我尝试了所有解决方案(将 IsReference=true 添加到 DataContract 属性......)。唯一可行的方法是用 Collection 实体中的 IgnoreDataMember 属性替换 DataMember 属性,但是我失去了双向关系,这是我想要这个特定实体的东西......

【问题讨论】:

    标签: wcf windows-phone ria cyclic-reference


    【解决方案1】:

    避免在数据合约中使用 n 级递归,因为反序列化它们时会遇到问题(可能导致堆栈溢出)。 考虑扁平化你的 DTO 结构。您可以在没有递归的情况下对父母和孩子之间的关系进行建模。

    或者,尝试确定需要支持的最大递归级别,并在您的 DTO 结构中明确建模。

    【讨论】:

    • 相当多。但是,我的模型已经是普通的旧 POCO 对象。这是否意味着我必须创建另一个扁平化 POCO 结构的类(DTO 对象)?我的意思是,这就像同时编写和维护两者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多