我正在使用 Entity Framework Core 和 ASP.NET Core 3.1。
我有两个简单的模型:
public class UserModel
{
public int UserModelId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Token { get; set; }
public List<TherapyModel> Therapies { get; set; }
}
public class TherapyModel
{
public int TherapyModelId { get; set; }
public int UserModelId { get; set; }
public string Title { get; set; }
public int Quantity { get; set; }
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
public bool Saturday { get; set; }
public bool Sunday { get; set; }
public string ImgBase64 { get; set; }
public string ImgUrl { get; set; }
public int UserModelForeignKey { get; set; }
public UserModel UserModel { get; set; }
}
现在,我用这种方式初始化一切:
public class DatabaseManager : DbContext
{
//Entities:
public DbSet<UserModel> UserModel { get; set; }
public DbSet<TherapyModel> TherapyModel { get; set; }
protected override void OnModelCreating( ModelBuilder modelBuilder )
{
modelBuilder.Entity<TherapyModel>().HasOne(p => p.UserModel)
.WithMany(s => s.Therapies)
.HasForeignKey(p => p.UserModelForeignKey);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseMySql( @"Server=127.0.0.1;database=test2;uid=root;pwd=" ); );
}
本地数据库已使用正确的外键正确填充。事实上这个查询返回 3 行:
select *
from usermodel
join therapymodel on therapymodel.UserModelForeignKey
但是,由于某种原因,当我尝试从 C# 代码获取 UserModel
时,它总是返回“Therapies”为 NULL。我通过这两种方式获取 UserModel
:
UserModel user = dbManager.UserModel.FirstOrDefault( user => user.UserModelId == iUserModel.UserModelId );
var users = dbManager.UserModel;
用户和用户的治疗均为 NULL。我实在不明白为什么。有什么帮助吗?
最佳答案
好吧,我终于找到了答案。通过阅读这篇文章:
https://www.learnentityframeworkcore.com/lazy-loading
我启用了延迟加载(默认情况下启用),但外键必须是虚拟的:
public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual List<Book> Books { get; set; } = new List<Book>();
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public virtual Author Author { get; set; }
}
现在它可以工作了,微软教程没有告诉你任何关于延迟加载和将外键声明为虚拟的事实。我希望这对将来的任何人都有帮助。
关于asp.net-core - Entity Framework Core 始终返回外部行的空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60210985/