简体   繁体   中英

EF Core circular reference on ASP.NET Core user class

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM