For example I want to perform a Select operation :
var payerData = this.context.Payers
.Where(x => x.Id == Data.ID)
.Select(x => new {
x.someID,
x.Status
});
Now I want to generalize this as an extension method so that it can be used with other tables also. Is it possible to do this? If yes, than how?
I tried to find the solution but everywhere it is given about LINQ and I want this in EF Core. And I am a beginner in .Net Core.
If you are asking how to reuse query for entities that share some of the properties, then you could:
Small demo below. I am not sure how to help with part of your question about using LINQ since whole EF Core is built around it
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace ConsoleApp5
{
public interface TypeWithFields
{
int Id { get; set; }
int SomeId { get; set; }
string Status { get; set; }
}
public class A : TypeWithFields
{
public int Id { get; set; }
public int SomeId { get; set; }
public string Status { get; set; }
}
public class B : TypeWithFields
{
public int Id { get; set; }
public int SomeId { get; set; }
public string Status { get; set; }
}
public class MyContext : DbContext
{
public MyContext(DbContextOptions options) : base(options)
{
}
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
}
public class QueryDto
{
public int Id { get; set; }
public int SomeId { get; set; }
public string Status { get; set; }
}
public static class DbContextExtensions
{
public static IQueryable<QueryDto> Filter<T>(this IQueryable<T> query, int id)
where T: TypeWithFields
{
return query.Where(x => x.Id == id)
.Select(x => new QueryDto
{
Id = x.Id,
SomeId = x.SomeId,
Status = x.Status
});
}
}
class Program
{
static void Main(string[] args)
{
var builder = new DbContextOptionsBuilder().UseInMemoryDatabase("memorydb");
var dbContext = new MyContext(builder.Options);
var queryAs = dbContext.As.Filter(1).ToList();
var queryBs = dbContext.Bs.Filter(1).ToList();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.