简体   繁体   中英

How can I change the schema of a type that implements a particular interface in an Entity Framework 6 Custom Convention?

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"; }

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; }
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM