例如我想执行选择操作:
var payerData = this.context.Payers
.Where(x => x.Id == Data.ID)
.Select(x => new {
x.someID,
x.Status
});
现在我想将其概括为一种扩展方法,以便它也可以与其他表一起使用。 是否有可能做到这一点?如果是,那么如何?
我试图找到解决方案,但到处都给出了有关 LINQ 的解决方案,我希望在 EF Core 中找到它。我是 .Net Core 的初学者。
最佳答案
如果您询问如何重用共享某些属性的实体的查询,那么您可以:
- 创建接口(interface)并将其应用到每个实体。
- 创建扩展方法并传递接口(interface)类型作为通用限制。
下面是小演示。 我不知道如何帮助您解决有关使用 LINQ 的部分问题,因为整个 EF Core 都是围绕它构建的
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();
}
}
}
关于c# - 如何使用 EF Core 在 .NET core 3.1(不带 LINQ)中创建用于 CRUD 操作的自定义扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63932057/