且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用实体框架的 C# 中的通用存储库

更新时间:2021-10-25 22:08:31

您可以使用 EF Core 提供的元数据服务,例如 FindEntityTypeFindPrimaryKey 以获取 PK 属性名称.然后,您可以使用它使用另一个 EF Core 提供的有用方法来访问 LINQ to Entities 查询中的 PK 值 EF.Property.

You can use EF Core provided metadata services like FindEntityType and FindPrimaryKey to get the PK property name. Then you can use it to access the PK value inside LINQ to Entities query using another EF Core provided useful method EF.Property.

像这样:

public virtual List<TEntity> GetByIds(int[] ids)
{
    var idName = _context.Model.FindEntityType(typeof(TEntity))
        .FindPrimaryKey().Properties.Single().Name;
    return Entities
        .Where(x => ids.Contains(EF.Property<int>(x, idName)))
        .ToList();
}