【问题标题】:How to avoid a relation-property to include its own relation?如何避免一个关系属性包含它自己的关系?
【发布时间】:2020-10-26 19:12:31
【问题描述】:
public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public string Id { get; set; }
    public string Username { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }
    public string Role { get; set; }
    public Organization Organization { get; set; }


}
public class Organization
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Phone { get; set; }
    public string AccessToken { get; set; }
    [ForeignKey("User")]
    public string UserId { get; set; }
    public User User { get; set; }
}

我首先使用 EF 代码创建了以下两个表。 我需要使用 Org 检索我的用户,但我不希望 Org 属性再次包含相同的用户。我怎样才能避免这种情况,所以我得到的只是组织的用户?

这是给我带来麻烦的一行:

        return await _context.Users.Include(x => x.Organization).FirstOrDefaultAsync(x => x.Id == id);

【问题讨论】:

    标签: c# entity-framework asp.net-core-webapi


    【解决方案1】:

    我需要使用 Org 检索我的用户,但我不希望 Org 属性再次包含相同的用户。

    要么删除 Organization.User 导航属性,或者,如果您只想从序列化输出中删除它,则使用 JsonIgnore(或类似的)装饰导航属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多