c# - 在实体框架核心迁移中,关系数据即将为空
问题描述
您好,我正在使用 ef 核心。如果我从数据库中获取数据,所有关系模型都将变为空,为什么会这样?如果我使用 Include 方法,我遇到的结果不是更改所有数据都是空的,除了上下文模型
那是我的代码。ef 核心迁移不自动包含数据吗?,TContext 是我的通用 dbContext
public TEntity Get(Expression<Func<TEntity, bool>> filter)
{
using (TContext context = new TContext())
{
var result = context.Set<TEntity>().SingleOrDefault(filter);
return result;
}
}
我尝试了另一个代码
public List<Products> GetData()
{
using (NervioDbContext context = new NervioDbContext())
{
var result = context.Products.
Include(a => a.Category).ToList();
return result;
}
}
也是我的产品模型和类别模型
public class Category
{
[Key]
public int CategoryId { get; set; }
[StringLength(50)]
public string CategoryName { get; set; }
public ICollection<Product> Product { get; set; }
}
public class Product
{
[Key]
public int ProductId { get; set; }
public int ProductQuantity { get; set; }
public string ProductName { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
解决方案
Ef不会自动带来相关数据
你应该使用LazyLoadingProxies
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
或使用时AddDbContext
:
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
但请注意加载所有相关数据不是一个好主意
推荐阅读
- php - Laravel 播种器:调用未定义的方法 Illuminate\Notifications\Notification::getConnectionName()
- c# - 如何使用 Magick.NET (imagemagick) 和 C# 将 APNG 转换为 WEBP?
- c# - 如何在 C# 中的索引器参数上设置 convertHighWaterMarkToRowVersion?
- kotlin - 为什么要为 ApplicationContext 对象添加注解 @ApplicationContext?
- here-api - 这里批量地理编码 API 停止工作 - HTTP 错误 500
- python - Scrapy Crawler:从页面中抓取列表
- javascript - cubiq - IScroll.js | 我应该在哪个方法生命周期中将自定义事件放入 React JS
- google-play - 我们如何在 Google Play 商店中禁用便利店付款?
- r - 一种计算有效的方法来查找每个 Type 2 行上方和下方的 Type 1 行的 ID?
- javascript - 你可以使用 backdraftjs watchable 让组件完全重新渲染吗?