0

I created an interface ILookupValue that I want all lookup values to inherit from.

public interface ILookupValue
{
    public bool Enabled { get; set; }
}

How can I determine if the current entitySet implements the interface so that I can set the schema for that entitySet to something other than the default?

I've tried the following, but it doesn't work:

public void Apply(EntitySet entitySet, DbModel model)
{
    ILookupValue lookupCheck = entitySet.GetType() as ILookupValue;
    if (lookupCheck != null) { entitySet.Schema = "lu"; }
}

Update: I've tried the following also, but get an object reference not set error.

if (typeof(ILookupValue).IsAssignableFrom(Type.GetType(entitySet.ElementType.Name))) { entitySet.Schema = "lu"; }
Alex Bello
  • 199
  • 2
  • 20
  • Figured out Entity Framework doesn't actually work with your types directly. It reads them through reflection and creates an EntityType that describes your type. If you need to work with your types directly, you need to get them directly from the assembly. See below. – Alex Bello Jul 29 '15 at 14:42

1 Answers1

0

Since EF doesn't actually use your types, you need to get them from the assembly. My biggest problem was that this convention was part of a library, so I didn't know ahead of time the assembly name and I couldn't find how to get it from the EF EntityType model. Therefore, I just created a static method that searches all loaded assemblies for the type name and returns it. I got the idea from this stackoverflow answer.

public static class TypeUtils
{
    public static Type FindType(string name)
    {
        return AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.IsDynamic)
                .SelectMany(a => a.GetTypes())
                .FirstOrDefault(t => t.Name.Equals(name));
    }
}

Then I updated my convention to find the type based on the EntitySet.ElementType.Name and then check to see if it implements the interface.

public void Apply(EntitySet entitySet, DbModel model)
{
    Type type = TypeUtils.FindType(entitySet.ElementType.Name);

    if (type != null)
    {
        if (typeof(ILookupValue).IsAssignableFrom(type)) { //make changes here; }
    }
}
Community
  • 1
  • 1
Alex Bello
  • 199
  • 2
  • 20