如果通过导航属性获取的实体框架数据不为空,则会导致错误

本文关键字:错误 数据 导航 属性 获取 框架 实体 如果 | 更新日期: 2023-09-27 18:27:10

我正在WCF服务,其中包含从现有数据库生成的.edmx文件。在乞求时存在问题,WCF级别数据已成功获取并发送,但在MVC Controller出现连接已关闭的错误,因为我知道这是因为Configuration.ProxyCreationEnabled = true;,当我将其更改为false时,一切似乎都很好,直到我尝试从多个表中获取数据, 哪些是链接的。

因此,.edmx文件中,有自动生成的类UserProfileRoles

public partial class UserProfile
{
    public UserProfile()
    {
        this.webpages_Roles = new HashSet<webpages_Roles>();
    }
    public int UserId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
}

public partial class webpages_Roles
{
    public webpages_Roles()
    {
        this.UserProfiles = new HashSet<UserProfile>();
    }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public virtual ICollection<UserProfile> UserProfiles { get; set; }
}

此外,在数据库中有表,其中包含

UserId
RoleId

据我了解,这被称为Navigation Property.我的问题是 - 当我尝试发送收集的数据时,例如:

List<UserProfile> result = Context.UserProfiles
            .Include(s => s.webpages_Roles)
            .Where(z => z.UserId == id)
            .ToList();

我收到的错误与Configuration.ProxyCreationEnabled错误相同。我还注意到,如果webpages_Roles Collection为空,一切正常,但如果至少有一条记录 - 我会收到错误消息。请帮帮我,解决它。

另外,我已经配置了服务来写入异常,消息是

webpages_Roles'包含循环,如果禁用引用跟踪,则无法序列化。

如果通过导航属性获取的实体框架数据不为空,则会导致错误

解决方案是用 UserProfilewebpages_Roles类装饰 [DataContract(IsReference = true)]属性

答案就在这个北极找到了