Get DbContext's DbSet<T> where T is variable

I have a DbContext looking somewhat like this:

class MyDbContext: DbContext
{
    public DbSet<Class1> Set1 {get;set;}
    public DbSet<Class2> Set2 {get;set;}
    ...
}

where Class1, Class2 ... : BaseClass
The thing is I'm reading data from xml and I use a dictionary that looks like this:

public class XmlNode
{
    public Func<BaseClass> CreateEntity { get; set; }
    ...
}

public static Dictionary<string, XmlNode> Nodes = new Dictionary<string, XmlNode>()
{
    ["Tag1"] = new XmlNode()
    {

        CreateEntity = () => new Class1(),
    }

    ...
}

And then I have to compare the read entity to an existing table and maybe add it. But I can't find a way to get the approptiate table without making a different function for every Class I have. Is there a way to get a DbSet where Class is a variable?

Upvotes: 0

Views: 2427

Answers (2)

reckface
reckface

Reputation: 5878

The DbContext your data context derives from has a method called Set(Type t) that accepts a type, type can be created from string.

For the scenario you've described you can create a DbSet from the string in your XML by

var typeName = "Some.Namespace.AndType";
DbSet t = Set(Type.GetType(typeName));

Note that you can't use linq or lambda expressions to query the resulting object, unless you cast it to a typed DbSet<T> or use a library like System.Linq.Dynamic which would allow you to call t.AsQueryable().Where("SomeProperty == @value");, but this should get you started.

Upvotes: 1

Asakuraa Ranger
Asakuraa Ranger

Reputation: 617

From how to check whether dbcontext sett exists in model you can just check if it exist then get DBset after checked

if(Exists<yourentity>())
{
   ... TEntity exist
}

from link

public bool Exists<TEntity>() where TEntity : class
{
    string entityName = typeof(TEntity).Name;
    ObjectContext objContext = ((IObjectContextAdapter)this).ObjectContext;
    MetadataWorkspace workspace = objContext.MetadataWorkspace;
    return workspace.GetItems<EntityType>(DataSpace.CSpace).Any(e => e.Name == entityName);
}

Upvotes: 0

Related Questions