EF Core circular reference on ASP.NET Core user class

asp.net-core c# entity-framework-core

Question

I'm looking for a little advice on EF Core with ASP.NET Core. In a nutshell, I'm looking for the best way to resolve a circular reference.

The basic premise is this: I have a User object that contains an ICollection of Character objects, and each Character object contains an associated user.

public class ApplicationUser : IdentityUser
{       
    public ICollection<Character> Characters { get; set; }
}
public class Character
{
    public Guid Id { get; set; }

    [Required]
    public ApplicationUser User { get; set; }

    // other properties
}

This doesn't seem to cause any issues within the application itself as EF deals with the circular reference without an issue. The problem is at the DB level I have two foreign keys on these two tables (AspNetUser and Characters) effectively pointing to each other, meaning that I would not be able to delete instances of either entity from the database as it would violate the corresponding foreign key constraint.

I'm somewhat new to ASP.NET Core so there is probably some convention or other which I have missed with regards to how users are handled. From an application point of view, I have a page that simply displays a list of characters along with the associated user's username. I'm currently thinking it might be best to remove the User property from the Character class and replace it with a UserId property (and have application logic to pull the correct user out of the UserManager), but I'm not sure this would get rid of the circular foreign key constraint.

1
0
8/1/2017 8:25:34 AM

Popular Answer

You need to add the parent user to the characters (one-to-many relationship) and make your collection virtual:

public class ApplicationUser : IdentityUser
{       
    public virtual ICollection<Character> Characters { get; set; }
}
public class Character
{
    public Guid Id { get; set; }

    public string ParentId { get; set; }

    public string UserId { get; set; }

    [Required]
    [ForeignKey("ParentId")]
    public virtual ApplicationUser Parent { get; set; }

    [Required]
    [ForeignKey("UserId")]
    public virtual ApplicationUser User { get; set; }

    // other properties
}
0
8/1/2017 11:43:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow