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

.NET Core 6升级后ApplicationDbContext转IObjectContextAdapter失败

.NET Core 6下获取实体主键值的解决方案

错误原因

你原来的代码依赖Entity Framework 6的IObjectContextAdapter接口,但.NET Core 6使用的是Entity Framework Core,ApplicationDbContext不再实现该接口,因此会抛出类型转换异常。

主键值获取方案

基于你已经能获取主键名称的代码,以下是获取对应主键值的实现方式:

单个主键场景

如果实体只有单个主键,可直接通过主键名称从CurrentValues中取值:

var keyName = entry.CurrentValues.EntityType.FindPrimaryKey().Properties
                   .Select(x => x.Name).Single();
// 获取主键值并转换为long类型
var keyValue = Convert.ToInt64(entry.CurrentValues[keyName]);

通用方案(支持复合主键)

如果需要兼容复合主键的场景,可遍历所有主键属性并收集键值对,完全替代原来的GetKeys方法:

public List<KeyValuePair<string, long>> GetKeys(EntityEntry entry)
{
    var keys = new List<KeyValuePair<string, long>>();
    var primaryKey = entry.CurrentValues.EntityType.FindPrimaryKey();

    if (primaryKey?.Properties != null)
    {
        foreach (var property in primaryKey.Properties)
        {
            var value = entry.CurrentValues[property.Name];
            keys.Add(new KeyValuePair<string, long>(property.Name, Convert.ToInt64(value)));
        }
    }

    return keys;
}

说明

EF Core中无需再依赖ObjectContext相关API,直接通过EntityEntry的CurrentValues(获取当前实体值)和EntityType(获取实体元数据)即可完成主键信息与值的获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:40:44