我有几个类都具有文件类型的 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>();
}
}
}
<块引用>
严重性代码描述项目文件行抑制状态 错误 CS1061“T”不包含“文件”的定义并且没有 可访问的扩展方法“文件”接受类型的第一个参数 可以找到“T”(您是否缺少 using 指令或程序集 参考?)
答案 0 :(得分:2)
编辑 您正在尝试为特定服务编写代码是通用的。您需要在 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 的应用程序,请参阅此 blog by Stephen Cleary 以获取完整详细信息,有关简要概述,请阅读 @IvanStoev 留下的评论