我创建了几个 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 属性,但是我失去了双向关系,这是我想要这个特定实体的东西......