Search code examples
asp.net-mvcentity-frameworkjavascriptserializeref-fluent-api

ScriptIgnore Attribute Being Ignored


I'm attempting to serialize a DTO however its falling down, claiming a circular reference issue - which is definitely valid. I have the following entities:

public class User {
    [Key]
    public int UserID { get;set; }
    public string EmailAddress { get;set; }
    // etc
    [ScriptIgnore]
    public virtual ICollection<Role> Roles { get;set; }
};

public class Role {
    [Key]
    public int RoleID { get;set; }
    // etc
    [ScriptIgnore]
    public virtual ICollection<User> Users { get;set; }
};

Both of these entities map to their namesakes in the database, as well as an intermediate table UserRoles which is not brought through but is mapped as a custom EntityTypeConfiguration

When I come to serialize the User object, an error occurs saying:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.User_7A469191462B9ADC27B374089E18004C2D72F0D107975B83F04E7A46145E1B1E'.

Obviously, by looking at both the User and Role classes, they both contain collections of each other which is why a circular reference error is generated but I would have assumed that by adding a ScriptIgnore attribute against the Users and Roles members, they would be ignored in this instance.


Solution

  • Ok, maybe I was too quick with my posting.

    This is the answer:

    ScriptIgnore, JsonSerializer not paying any attention?

    Using the [ScriptIgnore(ApplyToOverrides = true)] parameter fixes it!