1

我正在尝试使用 .NET Core EF 和 Code First 加载相关实体,但是我收到以下错误:-

System.InvalidOperationException: The property 'Roles' is not a navigation property of entity type 'ApplicationUser'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.

我的 2 个模型如下所示

public class Role
{
    public short Id { get; set; }
    public string Name { get; set; }

    public ICollection<ApplicationUser> Users { get; set; }
}

public class ApplicationUser
{
    public long Id { get; set; }

    [Required(ErrorMessage = "This field is required")]
    public string Name { get; set; }
    [Required(ErrorMessage = "This field is required")]
    public string Surname { get; set; }
    public string HomeNo { get; set; }
    public string MobNo { get; set; }
    public short RoleId { get; set; }

    public string UserName { get; set; }
    [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }
    public string Password { get; set; }

    public Role Role { get; set; }

我的上下文如下所示:-

        modelBuilder.Entity<Role>().ToTable("Role");

        modelBuilder.Entity<ApplicationUser>().HasOne(c => c.Role)
                                        .WithMany(r => r.Users)
                                        .HasForeignKey(c => c.RoleId);
        modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUser");

我正在尝试通过以下方法获取验证用户:-

   var verifiedUser = await GetById<ApplicationUser>(m => m.Email == user.Email, "Roles");

这反过来又调用了一个 GenericService :-

    public async Task<T> GetById<TKey>(
        Expression<Func<T, bool>> filter = null,
        string includeProperties = "")
    {
        return await _genericRepository.Get<T>(filter, includeProperties);
    }

最后是 GenericRepository:-

    public async Task<T> Get<TKey>(Expression<Func<T, bool>> filter = null, string includeProperties = "")

    {
        IQueryable<T> query = Context.Set<T>();
        query = IncludePropertiesQuery(query, includeProperties);

        if (filter != null)
        {
            query = query.Where(filter);
        }

        return await query.SingleOrDefaultAsync();
    }

IncludePropertiesQuery 看起来像这样:-

    private IQueryable<T> IncludePropertiesQuery(IQueryable<T> query, string includeProperties = "")
    {
        if (includeProperties == null)
        {
            includeProperties = "";
        }

        includeProperties = includeProperties.Trim() ?? string.Empty;
        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        return query;

    }

这与我的 DbContext 以及我在 2 个表之间的关系有关吗?

感谢您的帮助和时间

4

2 回答 2

0

显然 EF7 中的自动延迟加载存在问题

在这里看到问题

所以我在获取用户后做了额外的步骤来获取实际角色

于 2017-04-11T09:55:16.950 回答
0

如果您的“includeProperties”参数为 null 或为空,则不能使用“Include”扩展方法。将逻辑添加到您的代码中以解决此问题。

于 2017-04-10T14:31:52.913 回答