0

我创建了几个 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
}

和 Collection 实体:

[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;
        }
    }
}

这按预期工作:我收到一个填充有数据成员和空集合数组的单个对象。

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

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

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

4

1 回答 1

0

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

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

于 2012-02-29T18:08:14.393 回答