I have code as follows:
Dictionary<object, object> dict = ...
Color = (int)dict.GetValue("color");
When I convert the Color to an int, I get the following exception:
System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.Int32'.
I am not sure why I can't just cast from a long to an int. I know for a fact that the value is less than 0xFFFFFF
(24 bits) since it is a color.
I tried using unchecked
but that didn't help either.
You must first unbox the value as the dictionary's value type is object
.
Dictionary<object, object> dict = ...
Color = (int)(long)dict.GetValue("color");
If you don't know the original type, the following idiom may be more convenient.
public T Get<T>(string key)
{
return (T) Convert.ChangeType(_dict[key], typeof(T), CultureInfo.InvariantCulture);
}
cannot be tracked because another instance with the same key value for is already being tracked
find solution
context.Patrol.AddRange(model); // error
entity.Property(e => e.Id)
.HasColumnName("ID")
.ValueGeneratedNever(); // old
entity.Property(e => e.Id)
.HasColumnName("ID"); //remove ValueGeneratedNever()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.