![](/img/trans.png)
[英]DbSet<TEntity>.Local.Any() performance issue when upgraging EF Core from 2.2.6 to 3.1.3
[英]using include on DbSet<TEntity> ef core
我有几个类都具有文件类型的 IEnumerable。 但我正在努力将包含与 DbSet 一起使用
public class FileRepository<T> : IFileRepository<T> where T : class
{
private readonly DataContext context;
private readonly DbSet<T> table = null;
public FileRepository(DataContext ctx)
{
context = ctx;
table = context.Set<T>();
}
public async Task<object> GetByIdAsync(long id)
{
if (id > 0)
{
return (await table
.Include(x => x.Files)
.FirstAsync(x => x.Id == id)
.ConfigureAwait(false))
.Files.ToList();
}
else
{
return new List<File>();
}
}
}
严重性代码 描述 项目文件行抑制 State 错误 CS1061“T”不包含“文件”的定义,并且找不到接受类型“T”的第一个参数的可访问扩展方法“文件”(您是否缺少 using 指令或装配参考?)
编辑您尝试为特定服务编写代码是通用的。 您需要在 T 上添加约束。
例如 T 是通用的,所以没有办法知道有一个属性。 Id 或 Files 在那里,将您的逻辑写在一个层中。
public class EmployeeFiles<Employee> : IFileRepository<Employee>
{
//... Write your logic here instead so the logic is specific to the Entity.
}
或者,您可以让所有要实现文件 api 的实体实现接口
public interface IHasFileProperties
{
public int Id {get; set;}
public ICollection<File> Files { get; set; }
}
并有文件回购:
IFileRepository<T> where T : IHasFileProperties
此外,从您提出的问题 GetById 应该返回 T 而不是文件列表,如果您想获取文件列表,您应该在现有存储库上进行扩展。
旁注: ASP.Net-core 摆脱了旧的同步上下文,因此您不再需要调用.ConfigureAwait(false))
,除非您使用的是针对较旧的 .net 4.5 或具有 UI 的应用程序的库,请参阅此由 Stephen Cleary 撰写的博客了解详细信息,有关简要概述,请阅读@IvanStoev 留下的评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.