Search code examples
c#entity-framework-4system.reflection

How to dynamically cast a property to an unknown class and perform a check on it in C# Entity Framework?


I'm trying to put a series of functions together for Entity Framework use. The idea is that I want to pass generic classes all into one routine, and then have the routine "type" it for me and act accordingly. I can't seem to figure out how to marry the Class back up with it's PropertyType.

        public void AddUpdate(string classType, Object o)
    {
        //This gets the Type of my Class Object ok.
        Type mType = Type.GetType(GetType().Namespace + "." + classType, true);

        var meContext = new ClsContext(_ConnectionString);

        //This retrieves the correct primary key for my the Class Object.
        string key = FncGetPrimaryKey(meContext, classType + "s");

        //I've tried this as a PropertyInfo as well instead of a Var
        var keyID = o.GetType().GetProperty(key);

        //I've tried this as Var as well as Dynamic 
        dynamic obj = o;

        //Now I'm stuck, because I want to evaluate the property,
        //but I get an error "<MyClass> does not contain a reference for 'keyID'

        if (obj.keyID == 0) //ERROR ON THIS LINE
        {
            meContext.Entry(o).State = EntityState.Added;
        }
        else
        {
            meContext.Entry(o).State = EntityState.Modified;
        }
        meContext.SaveChanges();
    }

Solution

  • Although, I did not fully understand why do you want it like this, I think, I understood what you are trying to achieve. This is how I do it in case if I want to add some common object:

    public void AddUpdate<T>(T obj) where T : IEntity
    {
        using(var ctx = new ClsContext(_ConnectionString))
        {
            if (obj.keyID == 0)
            {
                ctx.Entry(o).State = EntityState.Added;
            }
            else
            {
                ctx.Entry(o).State = EntityState.Modified;
            }
            ctx.SaveChanges();
        }
    }
    
    public interface IEntity
    {
        int keyId {get;set;}
    }