You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF6的System.Data.Entity.Core.EntityKey在EF Core中的等价类型是什么?

EF6 迁移至 EF Core 时 EntityKey 的等效处理方案

EF Core 重构了实体键的底层管理逻辑,不存在与 EF6 中 System.Data.Entity.Core.EntityKey 完全对等的公共 CLR 类型,也不会在实体类中插入该类型的内置属性,你可以根据原代码的实际业务目的选择对应的实现方式:

  • 如果你添加该判断仅为了过滤 EF6 自动注入到实体类中的 EntityKey 类型内置属性:EF Core 不存在这类注入到实体的公共属性,直接删除该判断条件即可。
  • 如果你需要过滤实体的主键、外键或 EF 内部维护的阴影属性,可以通过 EF Core 的模型元数据 API 实现,参考代码如下:
PropertyInfo[] propInfo = myObject.GetType().GetProperties();
// 需传入当前使用的 DbContext 实例
var entityType = dbContext.Model.FindEntityType(typeof(T));
foreach (PropertyInfo col in propInfo)
{
    // 排除主键属性
    bool isPrimaryKey = entityType?.FindPrimaryKey()?.Properties.Any(p => p.Name == col.Name) ?? false;
    // 排除EF内部维护的阴影属性
    bool isShadowProperty = entityType?.FindProperty(col.Name)?.IsShadowProperty() ?? false;
    
    if (!isPrimaryKey && !isShadowProperty)
    {
        // 执行原有的业务逻辑
    }
}
  • 如果你需要实现类似 EF6 中获取实体键信息的能力,可以封装扩展方法实现:
/// <summary>
/// 获取实体的主键名和对应值
/// </summary>
public static (IReadOnlyList<string> KeyNames, IReadOnlyList<object?> KeyValues) GetEntityKey<T>(this DbContext dbContext, T entity)
{
    var entityType = dbContext.Model.FindEntityType(typeof(T)) 
        ?? throw new ArgumentException($"类型{typeof(T).Name}不在当前上下文的模型中");
    var primaryKey = entityType.FindPrimaryKey() 
        ?? throw new ArgumentException($"类型{typeof(T).Name}未定义主键");
    
    var keyNames = primaryKey.Properties.Select(p => p.Name).ToList();
    var keyValues = primaryKey.Properties.Select(p => p.GetGetter().GetClrValue(entity)).ToList();
    return (keyNames, keyValues);
}

内容的提问来源于stack exchange,提问作者SrB30

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:18:03