C# 实体框架不适用于外键接口
我用Ientity接口签署了我的整个数据库模型C# 实体框架不适用于外键接口,c#,.net,C#,.net,我用Ientity接口签署了我的整个数据库模型 public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null) { using (TContext context = new TContext()) { return filter == null ? context.Set&
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 List GetAll(表达式过滤器=null)
{
使用(TContext context=new TContext())
{
返回筛选器==null?
context.Set().ToList():
context.Set().Where(filter.ToList();
}
}
}
公共类产品:智能化
{
[关键]
[必需]
public int ProductId{get;set;}
//.....
[外国钥匙(“类别”)]
公共虚拟ProductCategories ProductCategories{get;set;}
public int CategoryId{get;set;}
}
公共类产品类别:通用性
{
[关键]
[必需]
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);
}
}
}
public类EsitProductContext:DbContext
{
公共数据库集产品{get;set;}
公共数据库集ProductCategories{get;set;}
公共DbSet ProductImages{get;set;}
配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
{
如果(!optionBuilder.IsConfigured)
{
选项生成器
.UseSqlServer(“…”)
.使用LazyLoadingProxy(错误);
}
}
}
我有一个分层架构,下面的代码是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();
}
}
}
public类EfEntityRepositoryBase:IEntityRepository
其中tenty:class、ienty、new()
其中TContext:DbContext,new()
{
//...
公共列表GetAll(表达式筛选器=null)
{
使用(TContext context=new TContext())
{
返回筛选器==null?
context.Set().ToList():
context.Set().Where(filter.ToList();
}
}
}
我的问题是,当我使用模型而不是TEntity接口时,我用foreing键指定的集合不会为null,但当我尝试使用实体接口时,为什么会为null
return context.Set<Products>().ToList(); //It works smoothly
返回context.Set().ToList()//它工作顺利
这不是C代码。请删除C
标记,除非有特殊原因包含该标记。如何通过将类型传递给TEntity来调用GetAll
方法?您不需要看到它,因为GetAll函数内部已为null。用断点观察这不是C代码。请删除C
标记,除非有特殊原因包含该标记。如何通过将类型传递给TEntity来调用GetAll
方法?您不需要看到它,因为GetAll函数内部已为null。带断点观看