c# - 实体框架不适用于外键接口
问题描述
我用 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
解决方案
推荐阅读
- php - php遍历由字符串而不是对象组成的数组
- python - 表中的 Python ReportLab 图片
- java - Java SOAP 将命名空间声明添加到 SOAP 主体的子元素
- swift - 来自另一个 viewController Swift 的 reloadData()
- c# - 在客户端中未定义的远程服务器上引发异常会导致“无法找到程序集”异常
- python-3.x - 尝试将 xlsx 文件保存到 S3 存储桶时出错
- spring - 升级到 Spring Boot 版本 2.3.1.Release 后应用程序无法启动
- python - Z3PY 将 Int 转换为 Python int
- git - 多个(超过 1 个)私有 Github 存储库连接到 cpanel - 无法创建第二个 cpanel 存储库
- google-app-engine - 如何在 2021 年增加 gcloud 应用部署超时