EF框架使用常见异常处理
同一个实体被多次tracked的问题
错误提示 The instance of entity type 'XXXX' cannot be tracked because another instance with the same key value for {'Key'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. 这里面的"XXXX"可能是任意一个实体模型的名称,"Key"则是这个实体的Key字段。出现这个错误的原因是试图更新某个实体时,拥有相同Key的另一个实体也被EF Core tracked了。常见以下情况:
Json字符串转换的对象赋值时
-
定义一个Json字符串对象
public class Root
{
///
///
///
public Signal signal { get; set; }
///
///
///
public Info info { get; set; }
///
///
///
public List<ListItem> list { get; set; } = new List<ListItem>();
} -
赋值
//异常写法
Info p_info= new Info();
p_info.value1="1";
root.info = p_info;//赋值1
Signal p_signal=new Signal();
p_signal.value1="测试";
root.signal = p_signal; //赋值2
string message = JsonConvert.SerializeObject(root); //转成Json字符串
//完成字符串发送后更新对应对象数据时提示异常//正常写法 创建新对象赋值,避免引用类型指向同一个地址
root.info = p_info.ToJson().JsonToObject<TDataModel.Info>(); //赋值1
root.signal = signal.ToJson().JsonToObject<TDataModel.Signal>(); //赋值2
string message = JsonConvert.SerializeObject(root);public static class JsonHelper
{
public static string ToJson(this object obj)
{
return JsonConvert.SerializeObject(obj);
}
///
/// JSON格式转换为对象
///
/// <param name="obj"></param>
/// <returns></returns>
public static T JsonToObject<T>(this string serialize) where T : class, new()
{
try
{
T deserialize = JsonConvert.DeserializeObject<T>(serialize);
return deserialize;
}
catch (Exception e)
{
throw new Exception($"JsonToObject 异常:{e}");
}
}
}
持续更新中。。。。