无法在实体框架中获取父类的子记录

时间:2018-02-23 17:22:35

标签: entity-framework

我在我的存储库中使用mysql作为后端数据库和EntityFrameworkCore。每个用户在上次登录时应该在另一个表中有相关​​记录。  当我尝试加载我的用户列表时,所有用户都回来时没有匹配的记录。不知道为什么。

获取用户的方法:

public IEnumerable<UserItem> GetUsers(Func<User, bool> query, int count, int skip)
{
    var users = new List<UserItem>();
    foreach (var user in context.User.Where(query).Skip(skip).Take(count))
    {
        users.Add(new UserItem()
        {
            FirstName = user.FirstName,
            LastLoginDate = user.UserLoginLog.Any()? user.UserLoginLog.OrderByDescending(x => x.DateLogged).FirstOrDefault().DateLogged : default(DateTime?),
            LastName = user.LastName,
            UserId = user.UserId,
            EmailAddress = user.EmailAddress,
            Approved = user.Approved,
            UserType = UserType.ParseFromValue(user.UserTypeId)
        });
    }

    return users;
}

用户类:

public partial class User
{
    public User()
    {
        UserLoginLog = new List<UserLoginLog>();
    }

    [Key]
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string Password { get; set; }
    public int UserTypeId { get; set; }
    public bool Approved { get; set; }
    public DateTime DateAdded { get; set; }

    public List<UserLoginLog> UserLoginLog { get; set; }
}

UserLoginLog类

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

    public DateTime DateLogged { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }
}

0 个答案:

没有答案