1

I've been given the task of porting an project written with Entity Framework 6 to Entity Framework Core 3.1.

I've done most of the job, but I can't find a solution for replacing ObjectContext. At the moment I'm facing this kind of problem:

    public static T FromObjectToStruct<T>(object o) where T : struct
    {
        // Cast the value read to type choice
        return (T) (o as T?).GetValueOrDefault();
    }


    /// <summary>
    /// Convert an object to a dictionary
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static Dictionary<string, object> ToDictionary<T>(this T obj) where T : class
    {
        var dictionary = new Dictionary<string, object>();
        var properties = ObjectContext.GetObjectType(obj.GetType()).GetProperties(
            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
        foreach (var p in properties)
        {
            dictionary.Add(p.Name, p.GetValue(obj, null));
        }

        return dictionary;
    }

    /// <summary>
    /// Returns the differences between two objects of the same type T
    /// </summary>
    /// <param name="obj1"></param>
    /// <param name="obj2"></param>
    /// <returns></returns>
    public static Dictionary<string, object> GetDiff<T>(this T obj1, T obj2) where T : class
    {
        var diff = new Dictionary<string, object>();
        var objType = ObjectContext.GetObjectType(obj1.GetType());
        var objProperties = objType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic |
                                                  BindingFlags.Public | BindingFlags.FlattenHierarchy);

        foreach (var objProperty in objProperties)
        {
            var objValue1 = objProperty.GetValue(obj1, null);
            var objValue2 = objProperty.GetValue(obj2, null);
            if (!Equals(objValue1, objValue2))
            {
                diff.Add(objProperty.Name, objValue2);
            }
        }

        return diff;
    }

Any hint or link to documentation that explains how to workaround the issue would be great.

Backs
  • 24,430
  • 5
  • 58
  • 85
ReneRam
  • 71
  • 9
  • Does this answer your question? [How to adapt IObjectContextAdapter from EF 6 to EF Core](https://stackoverflow.com/questions/43957517/how-to-adapt-iobjectcontextadapter-from-ef-6-to-ef-core) – Jan Feb 04 '20 at 12:14
  • What were you using ObjectContext for in EF 6? Get the entity's properties? A proxy object *inherits* from the entity type. You could just get the properties from the type you have, or use `Type.BaseType` to get the entity type from the proxy type. – Panagiotis Kanavos Feb 04 '20 at 12:15

0 Answers0