我正在尝试首先使用.NET核心EF和代码加载相关实体,但我收到以下错误:-
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.我的两个模型如下所示
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");我正在尝试以如下方式获取verifiedUser:
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和我在两个表之间的关系有关吗?
感谢您的帮助和时间
发布于 2017-04-10 22:31:53
如果"includeProperties“参数为null或空,则不能使用"Include”扩展方法。在你的代码中添加逻辑来解决这个问题。
https://stackoverflow.com/questions/43325880
复制相似问题