且构网

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

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

更新时间:2022-11-04 21:27:54

您可以使用EF Core提供的元数据服务,例如 FindEntityType FindPrimaryKey 以获取PK属性名称。然后,您可以使用它来使用另一个EF Core提供的有用方法 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();
}