Search code examples
c#entity-frameworkwcflinq-to-entitiesnavigation-properties

If Entity Framework data obtained via navigation properties isn't empty, it causes error


I'm having WCF service, with included .edmx file, generated from existing data base. At the begging there were problem, that at WCF level data was successfully obtained and sent, but in MVC Controller appeared error that connection was closed, as I understood that was because of Configuration.ProxyCreationEnabled = true; , when I changed it to false, everything seemed to work fine, until I've tried to get data from multiple tables, which are linked.

So, .edmx file, there are auto generated classes UserProfile and Roles

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

And

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

Also, in Database there is table which consist of

UserId
RoleId

As I understood, this is called Navigation Property. My problem is - when I'm trying to send data gathered like:

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

I'm receiving same error as than Configuration.ProxyCreationEnabled was true. Also I've noticed that in case where webpages_Roles Collection is empty, everything works fine, but if there are at least one record - I'm receiving error message. Please help me, solve it.

Also, I've configured service to write exceptions, and the message was

webpages_Roles' contains cycles and cannot be serialized if reference tracking is disabled.'.


Solution

  • Solution is to decorate UserProfile and webpages_Roles classes with [DataContract(IsReference = true)] attribute

    The answer was found in this arcticle