首页 > 解决方案 > 在实体框架核心迁移中,关系数据即将为空

问题描述

您好,我正在使用 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; }
}

标签: c#entity-framework-core

解决方案


Ef不会自动带来相关数据

你应该使用LazyLoadingProxies

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);

或使用时AddDbContext

.AddDbContext<BloggingContext>(
    b => b.UseLazyLoadingProxies()
          .UseSqlServer(myConnectionString));

但请注意加载所有相关数据不是一个好主意

了解更多信息


推荐阅读