5

I have a model like

public class User
{
    [Key]
    public long UserId { get; set; }

    [Required]
    public String Nickname { get; set; }

    public virtual ICollection<Group> Memberships { get; set; }
}

public class Group
{
    [Key]
    public long GroupId { get; set; }

    [Required]
    public String Name { get; set; }

    public virtual ICollection<User> Members { get; set; }
}

public class DataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Group> Groups { get; set; }

    public DataContext()
    {
        Configuration.LazyLoadingEnabled = true;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
        .HasMany(u => u.Memberships)
        .WithMany(t => t.Members)
        .Map(x =>
        {
            x.MapLeftKey("UserId");
            x.MapRightKey("GroupId");
            x.ToTable("GroupMembers");
        });
    }
}

All goes fine when accessing the entities using a test console application, but I need to have this through a WCF service, here I got this exception:

Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service

The only way I found to have this working is, removing the navigator in one of the entities, because having the navigators in both sides causes a infinite looping.

Is there a way to have this working without removing the navigators?

4

1 回答 1

7

如果您尝试使用 WCF,则会出现两个问题:

  • 第一个问题:是否也要返回相关实体?使用 WCF / 序列化时始终关闭延迟加载,并确保手动使用 Include 来处理您真正想要返回的关系。否则延迟加载将加载对象图中的所有关系。此外,根据您的服务处理上下文生命周期的方式,延迟加载可能会在上下文已被释放时发生。
  • 您必须告诉序列化程序有关循环引用或删除循环引用。WCF 默认使用DataContractSerializer. 要删除循环引用,您可以使用属性标记其中一个导航属性,或者您可以通过使用属性标记所有实体和应该使用属性序列化的所有成员属性IgnoreDataMember来简单地告诉序列化程序循环引用。DataContract(IsReference = true)DataMember
于 2012-07-30T08:34:09.687 回答