EF核心查询多对多关系

时间:2019-02-20 19:24:29

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

我建立了一个“用户到用户角色”多对多关系,类似于此处的示例。 https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

但是,当我尝试查询Users时,它会按预期返回用户,但是UserRoles(示例中的BookCategories)始终为null。我需要使用Include()和ThenInclude()吗?我尝试使用每种方法,但这似乎也不起作用。

我已经尝试过类似的事情

var users = _context.TFCpUserTests.Include(e => 
e.TFCpUserRoleTests).ThenInclude(e => e.TFCpRoleTest);

但是由于某些原因我不能使用ThenInclude()。这是我正在使用的模型

public class TFCpRoleTest
    {

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<TFCpUserRoleTest> TFCpUserRoleTests { get; set; }
    }

public class TFCpUserTest
    {
        public int Id { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Username { get; set; }

        public string Email { get; set; }
        public byte[] PasswordHash { get; set; }
        public byte[] PasswordSalt { get; set; }

        public virtual ICollection<TFCpUserRoleTest> TFCpUserRoleTests { get; set; }
    }

public class TFCpUserRoleTest
    {
        public int UserId { get; set; }
        public virtual TFCpUserTest TFCpUserTest { get; set; }

        public int RoleId { get; set; }
        public virtual TFCpRoleTest TFCpRoleTest { get; set; }
    }

0 个答案:

没有答案