我正在尝试使用 .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 个表之间的关系有关吗?
感谢您的帮助和时间