Reputation: 5294
I have several classes that all have IEnumerable of type File. but I am struggling to use include with 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>();
}
}
}
Severity Code Description Project File Line Suppression State Error CS1061 'T' does not contain a definition for 'Files' and no accessible extension method 'Files' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
Upvotes: 1
Views: 1302
Reputation: 20987
EDIT You're attempting to write code for a specific service is a generic. You need to add constraints on T.
e.g T is Generic so there is no way to know there is a property. Id or Files on there, write your logic in a layer up.
public class EmployeeFiles<Employee> : IFileRepository<Employee>
{
//... Write your logic here instead so the logic is specific to the Entity.
}
Alternatively you can have all Entity which you want to implement the file api implement an inteface
public interface IHasFileProperties
{
public int Id {get; set;}
public ICollection<File> Files { get; set; }
}
and have the file repo:
IFileRepository<T> where T : IHasFileProperties
Additionally from the problem you presented GetById should return T and not a list of Files, if you want to get the list of files you should make an extension on your existing repo.
Side-Note: ASP.Net-core got rid of the legacy synchronization context so you don't need to call .ConfigureAwait(false))
anymore unless you're using a library targeting the older .net 4.5 or apps with UI, see this blog by Stephen Cleary for the full detail, for a brief overview read the comments left by @IvanStoev
Upvotes: 2