How to get name of schema from entity framework?

拈花ヽ惹草 提交于 2019-12-10 17:56:09

问题


I have following code

using (WdmEntities context = new WdmEntities())
{
    //get object models from context
    ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
    var container = objContext.MetadataWorkspace.GetEntityContainer(objContext.DefaultContainerName, DataSpace.CSpace);
    List<string> schemas = new List<string>();
    foreach (var set in container.BaseEntitySets)
    {
        foreach (var metaproperty in set.MetadataProperties)
        {
            //here 
            if(metaproperty.Name == "Schema")
            {
                //but metaproperty.Value == NULL
                schemas.Add(metaproperty.Value);
            }
        }
    }
}

I get null values instead of schemas names. How i can get names of shemas from entity framework. (In my db i have two different shemas.) Maybe someone knows another way?


回答1:


I had the wrong approach. The code bellow shows how i was able to get the name of the schemes.

using (WdmEntities context = new WdmEntities())
{
    //get object models from context
    ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
    //get all full names types from object model
    var fullNameTypes = objContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace);
    ///////////////////
    var conStr = objContext.Connection.ConnectionString;
    var connection = new EntityConnection(conStr);
    var workspace = connection.GetMetadataWorkspace();

    var entitySets = workspace.GetItems<EntityContainer>(DataSpace.SSpace).First().BaseEntitySets;

    for (int i = 0; i < fullNameTypes.Count; i++)
    {
        Type type = Type.GetType(fullNameTypes[i].FullName);
        string schema = entitySets[type.Name].MetadataProperties["Schema"].Value.ToString();   
    }
}



回答2:


Try this. It is well tested. Let me know if any doubt.

using (var context = new WdmEntities())
                {
                    //get object models from context
                    var objContext = ((IObjectContextAdapter)context).ObjectContext;
                    var items = objContext.MetadataWorkspace.GetItems<EntityContainer>(DataSpace.SSpace);
                    var container = items != null ? items.First() : null;
                    var schemas = new List<string>();
                    if(container != null)
                        schemas = container.BaseEntitySets.Select(set => set.Name).ToList();
                }


来源:https://stackoverflow.com/questions/18587865/how-to-get-name-of-schema-from-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!