How I get the Model Class to when I am passing in a generic in my method?

302 Views Asked by At

I m using tracker-enabled-dbcontext and using documentation to capture DB audit logs, configure tracking we need to be used

EntityTracker
.TrackAllProperties<NormalModel>()
.Except(x => x.Description)
.And(x => x.Id);

I have multiple Model classes so I decide to control the configuration dynamically. so I need to retrieve the Model class using namespace and pass it to the TrackAllProperties method.

I tried to like this,

Type test = Type.GetType("Mark.Domain.assets.AssetsSettings");
TrackerEnabledDbContext.Common.Configuration.EntityTracker.TrackAllProperties<test>();

but it does not accept "test" Type

This is the TrackAllProperties method. I'm not allowed to modify the following method

public static TrackAllResponse<T> TrackAllProperties<T>()
    {
        OverrideTracking<T>().Enable();

        var allPublicInstanceProperties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        //add high priority tracking to all properties
        foreach (var property in allPublicInstanceProperties)
        {
            Func<PropertyConfiguerationKey, TrackingConfigurationValue, TrackingConfigurationValue> factory =
                (key,value) => new TrackingConfigurationValue(true, TrackingConfigurationPriority.High);

            TrackingDataStore.PropertyConfigStore.AddOrUpdate(
                new PropertyConfiguerationKey(property.Name, typeof (T).FullName),
                new TrackingConfigurationValue(true, TrackingConfigurationPriority.High),
                factory
                );
        }

        return new TrackAllResponse<T>();
    }

How I can achieve this task

1

There are 1 best solutions below

3
John Glenn On

To pass the generic type, try this code instead:

TrackerEnabledDbContext.Common.Configuration.EntityTracker.TrackAllProperties<Mark.Domain.assets.AssetsSettings>();

The generic type argument T should be the actual model class rather than a type object of the model class. It's the same construct as declaring a List<string> - you don't have to get a type object for string.

Update:

In response to your comment, here is some code that you could try to get this working with variables, but I do not recommend this approach. You can read more about the Invoke call here. It may need to be modified to fit your application. Again, I do not recommend this approach.

var method = typeof(TrackerEnabledDbContext.Common.Configuration.EntityTracker).GetMethod("TrackAllProperties");
var trackMethod = method.MakeGenericMethod(test); // your type variable
trackMethod.Invoke(TrackerEnabledDbContext.Common.Configuration.EntityTracker, null);