简体   繁体   English

关于ASP.NET Core用户类的EF Core循环参考

[英]EF Core circular reference on ASP.NET Core user class

I'm looking for a little advice on EF Core with ASP.NET Core. 我正在寻找有关带有ASP.NET Core的EF 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. 基本前提是:我有一个User对象,其中包含一个Character对象的ICollection,并且每个Character对象都包含一个关联的用户。

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. 由于EF处理循环引用没有问题,因此这似乎不会在应用程序内部引起任何问题。 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. 问题是在数据库级别,我在这两个表上有两个外键(AspNetUser和Characters)有效指向彼此,这意味着我将无法从数据库中删除任何一个实体的实例,因为它将违反相应的外键关键约束。

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. 我是ASP.NET Core的新手,因此关于如何处理用户,我可能错过了一些约定或其他约定。 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. 我目前正在考虑最好从Character类中删除User属性,然后将其替换为UserId属性(并具有将正确的用户从UserManager中拉出的应用程序逻辑),但是我不确定这样做是否会成功摆脱了循环外键约束。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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