我需要帮助我的新项目进行学习。我正在使用linq和EF,并从数据库获取数据。但显示我的代码在以下错误]
该班级有很多科目:第1级有这些科目清单英语,科学,数学错误:
InvalidOperationException:生成警告错误'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning':试图延迟加载导航属性“ ClassSubject”“ SubjectProxy”类型的独立实体。不支持延迟加载用于分离的实体或已加载的实体'AsNoTracking()'。可以抑制或记录此异常将事件ID'CoreEventId.DetachedLazyLoadingWarning'传递给'DbContext.OnConfiguring'中的'ConfigureWarnings'方法或'AddDbContext'。pri
vate readonly IGenericRepository<Subject> _subject;
private readonly IGenericRepository<ClassSubject> _classSubject;
public SubjectService(IGenericRepository<Subject> subject, IGenericRepository<ClassSubject> classSubject)
{
_subject = subject;
_classSubject = classSubject;
}
public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
{
var _dbs = await _classSubject.AllAsync().ConfigureAwait(false);
return _dbs.Select(x => new ClassSubjectLib
{
ClassDetailsId = Convert.ToString(x.ClassDetailsId),
SubjectId = Convert.ToString(x.SubjectId),
SubjectInfo = _subject.FindBy(s => s.SubjectId == x.SubjectId)
});
}
public class ClassSubjectLib
{
public int ClassSubjectId { get; set; }
public string ClassDetailsId{ get; set; }
public string SubjectId { get; set; }
public IEnumerable<Subject> SubjectInfo { get; set; }
}
public class Subject
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SubjectId { get; set; }
[Column(TypeName = "VARCHAR(100)")]
public string SubjectName { get; set; }
public bool IsShow { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual ICollection<ClassSubject> ClassSubject { get; set; }
}
public class ClassSubject
{
[Key]
public int ClassSubjectId { get; set; }
public int ClassDetailsId { get; set; }
public int SubjectId { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual Subject Subject { get; set; }
public virtual ClassDetails ClassDetails { get; set; }
}
我需要类似数据
{
"ClassSubjectId": 1,
"ClassDetailsId": 1,
"SubjectInfo": [{
"SubjectName": "Abc",
"SubjectId": 1
}, {
"SubjectName": "cfd",
"SubjectId": 2
}]
}
摆脱无用的额外存储库层,然后做类似的事情:
public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
{
return dbContext.Set<ClassSubject>()
.Select(x => new ClassSubjectLib
{
ClassDetailsId = Convert.ToString(x.ClassDetailsId),
SubjectId = Convert.ToString(x.SubjectId),
SubjectInfo = x.Subjects.ToList()
})
.ToListAsync();
}
如错误消息所述,一旦您使用AsNoTracking()
,由于无法再加载导航属性,因此延迟加载不起作用。