首页 > 解决方案 > 实体框架不适用于外键接口

问题描述

我用 Ientity 接口签署了我的整个数据库模型,

   public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null)
    {
        using (TContext context = new TContext())
        {
            return filter == null ?
                context.Set<TEntity>().ToList() :
                context.Set<TEntity>().Where(filter).ToList();
        }
    }
    }

     public class Products:IEntity
    {
        [Key]
        [Required]
        public int ProductId { get; set; }
           //.....
        [ForeignKey("CategoryId")]
        public virtual ProductCategories ProductCategories { get; set; }
        public int CategoryId { get; set; }
    }




    public class ProductCategories: IEntity
    {

        [Key]
        [Required]
        public int ProductCatId { get; set; }

          //...
    }

我添加了数据库上下文

 public class EsitProductContext:DbContext
    {
        public DbSet<Products> Products { get; set; }
        public DbSet<ProductCategories> ProductCategories { get; set; }
        public DbSet<ProductImage> ProductImages { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            if (!optionsBuilder.IsConfigured)
            {

                optionsBuilder
                    .UseSqlServer("...")
                    .UseLazyLoadingProxies(false);

            }
        }

    }

我有一个分层架构,下面的代码是 DAL 层的一部分,

  public class EfEntityRepositoryBase<TEntity, TContext> : IEntityRepository<TEntity>
          where TEntity : class, IEntity, new()
        where TContext : DbContext, new()
    {

     //...
  public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null)
        {
            using (TContext context = new TContext())
            {
                return filter == null ?
                    context.Set<TEntity>().ToList() :
                    context.Set<TEntity>().Where(filter).ToList();
            }
        }
   }

我的问题是,当我使用我的模型而不是 TEntity 接口时,我用外键指定的 Collection 不为空,但是当我尝试使用实体接口时,为什么它为空?

 return context.Set<Products>().ToList(); //It works smoothly

标签: c#.net

解决方案


推荐阅读