实体框架核心从数据库获取关系

时间:2018-07-09 17:31:45

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

也许我的模型设置不正确,或者我期望EF做的工作比实际要多,但是...

我有一个User模型和一个UserRole模型。 User和UserRole之间存在1对1的关系。当我登录时,用户的UserRole为null,但UserRoleId不为null。此后,我已经设置了登录功能来手动获取与UserRoleId相匹配的UserRole,但是不应该隐式建立这种关系吗?

AuthController.cs
public class AuthController : Controller
{
    private readonly IAuthRepository _repo;
    private readonly IConfiguration _config;
    private readonly IMapper _mapper;

    public AuthController(IAuthRepository repo, IConfiguration config, IMapper mapper)
    {
        _mapper = mapper;
        _config = config;
        _repo = repo;
    }

   [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
    {
        var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

       //<!<!<! userFromRepo has a NULL UserRole property !>!>!>

        if (userFromRepo == null)
            return Unauthorized();

        // generate token...

        var user = _mapper.Map<UserForListDto>(userFromRepo);
        return Ok(new {tokenString, user}
    }
型号\ User.cs
public class User
{
    public int Id { get; set; }

    public string Username { get; set; }

    public int? UserRoleId { get; set; }
    public UserRole UserRole { get; set; }

    //other user attributes
}
型号\ UserRole.cs
public class UserRole
{
    public int Id { get; set; }

    public string Role { get; set; }
}
数据\ AuthRepository.cs
public class AuthRepository : IAuthRepository
{
    private readonly DataContext _context;

    public AuthRepository(DataContext context)
    {
        _context = context;
    }

    public async Task<User> Login(string username, string password)
    {
        var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == username);

        if (user == null)
            return null;

        if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
            return null;

        //this is how I'm currently linking the User to it's UserRole
        user.UserRole = await _context.UserRoles.FirstOrDefaultAsync(x => x.Id == user.UserRoleId);

        // auth successful
        return user;
    }
数据\ DataContext.cs
public class DataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }

    //I do not have an explicit relation between Users and UserRoles in OnModelCreating
}

1 个答案:

答案 0 :(得分:0)

您也可以尝试指定外键,如下所示:

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

    public string Username { get; set; }

    public int? UserRoleId { get; set; }

    [ForeignKey("UserRoleId")]
    public UserRole UserRole { get; set; }

    //other user attributes
}

EF可以自动执行此操作,但是您必须向UserRole类添加另一个属性。

public List<User> Users { get; set; }

有关此信息,请访问EF文档网站:EF-Core Data Annotations