实体框架不返回相关对象

时间:2016-11-16 22:07:39

标签: asp.net-mvc entity-framework asp.net-core

所以我试图将两个表相互关联起来。我有一个产品表和一个图像表。我在产品对象中有一组图像,在图像对象/表中有一个产品ID,但是当它获得产品对象时,图像集合是空的。

现在有趣的是,在调试时,如果我在产品对象从中提取信息之前检查了context元素,它会将图像加载到context元素中,然后它将被分配给产品。因此,只有当我手动检查上下文元素并且然后搜索图像时,它才有效。

产品

public class Product
    {
        public int Id { get; set; }
        public string FriendlyUrl { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public double? Price { get; set; }
        public double? Weight { get; set; }
        public int? Stock { get; set; }
        public virtual ICollection<Image> Images { get; set; }
    }

图片

public class Image
    {
        public int Id { get; set; }
        public int ProductId { get; set; }
        public string FileName { get; set; }
    }

的DbContext

 public class TheContext : DbContext
    {
        public TheContext(DbContextOptions<TheContext> options) : base(options)
        {

        }

        public DbSet<Product> Products { get; set; }
        public DbSet<Image> Images { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().HasMany<Image>(s => s.Images);
        }
    }

数据访问

public Product GetById(string id)
        {
            Product product = _context.Products.FirstOrDefault(p => p.FriendlyUrl == id);
            return product;
        }

2 个答案:

答案 0 :(得分:1)

您需要加载相关实体,例如图片:

数据访问

public Product GetById(string id)
{
    Product product = _context.Products.include(p => p.Images)
                              .FirstOrDefault(p => p.FriendlyUrl == id);
    return product;
}

在此处详细了解如何加载相关实体:https://msdn.microsoft.com/en-us/data/jj729737

此外,您希望尽快处理您的上下文,以避免内存泄漏,使用工厂或在需要的地方实例化上下文。

数据访问

public Product GetById(string id)
{
    using(var context = new TheContext())
    {
        product = context.Products.include(p => p.Images)
                         .FirstOrDefault(p => p.FriendlyUrl == id);
        return product;
    }
}

不要将上下文保持在字段变量中。

在此处详细了解生命周期:{{3}}

答案 1 :(得分:0)

这是由于EF延迟加载功能造成的。它似乎已经关闭了。 含义:您需要明确指定要加载的内容。如果它已打开,则首次访问时将加载集合

您可以在此处详细了解

https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext.aspx

Entity Framework Code First Lazy Loading