简体   繁体   中英

How to get Schema name from Entity Framework 4.0 objects?

I'm creating some manual SQL updates using C#, Entity Framework 4 and DB2, in the way of this naive example...

var UpdateCommand = "UPDATE MY_SCHEMA." + this.Entities.PRODUCT.EntitySet.Name +
                    " SET STOCK=0";
var AffectedRows = this.Entities.ExeceuteStoreCommand(UpdateCommand);

I want to specify the schema as with the entity name (which later, if implememented in a reusable library method, could be passed as parameter). So, I tried...

var Container = this.Entities.MetadataWorkspace.GetEntityContainer(this.Entities.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
var Set = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true);
var SchemaName = Set.MetadataProperties["Schema"].Value;

The problem is that the SchemaName returned is always null!

I've seen solutions based on parsing SQL generated by Entity Framework, but that could be fooled (text can containg anything), or SQL-Server specific. The idea is to be as DB agnostic as EF is.

Question is... how to get an entity schema name from EF objects, not parsing generated SQL and being db-agnostic?

you can get it from SSpace.

In ef5 following works. Probably will work in ef4 also

// for code-first
var Container = this.Entities.MetadataWorkspace.GetEntityContainer("CodeFirstDatabase", DataSpace.SSpace);
// db-first
var Container = this.Entities.MetadataWorkspace.GetEntityContainer("DbFirstModelStoreContainer", DataSpace.SSpace);

var schemaName = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true).Schema
// or
var set = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true);
var schemaName = Set.MetadataProperties["Schema"].Value;

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