本文整理汇总了C#中System.Data.Metadata.Edm.StoreItemCollection类的典型用法代码示例。如果您正苦于以下问题:C# StoreItemCollection类的具体用法?C# StoreItemCollection怎么用?C# StoreItemCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StoreItemCollection类属于System.Data.Metadata.Edm命名空间,在下文中一共展示了StoreItemCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateWrappedMetadataWorkspace
private static MetadataWorkspace CreateWrappedMetadataWorkspace(string metadata, IEnumerable<string> wrapperProviderNames)
{
MetadataWorkspace workspace = new MetadataWorkspace();
// parse Metadata keyword and load CSDL,SSDL,MSL files into XElement structures...
var csdl = new List<XElement>();
var ssdl = new List<XElement>();
var msl = new List<XElement>();
ParseMetadata(metadata, csdl, ssdl, msl);
// fix all SSDL files by changing 'Provider' to our provider and modifying
foreach (var ssdlFile in ssdl)
{
foreach (string providerName in wrapperProviderNames)
{
ssdlFile.Attribute("ProviderManifestToken").Value = ssdl[0].Attribute("Provider").Value + ";" + ssdlFile.Attribute("ProviderManifestToken").Value;
ssdlFile.Attribute("Provider").Value = providerName;
}
}
// load item collections from XML readers created from XElements...
EdmItemCollection eic = new EdmItemCollection(csdl.Select(c => c.CreateReader()));
StoreItemCollection sic = new StoreItemCollection(ssdl.Select(c => c.CreateReader()));
StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader()));
// and create metadata workspace based on them.
workspace = new MetadataWorkspace();
workspace.RegisterItemCollection(eic);
workspace.RegisterItemCollection(sic);
workspace.RegisterItemCollection(smic);
return workspace;
}
示例2: CreateObjectsScript
/// <summary>
/// Helper function for generating the scripts for tables & constraints.
/// </summary>
/// <param name="itemCollection"></param>
/// <returns></returns>
internal static List<string> CreateObjectsScript(StoreItemCollection itemCollection, bool returnWarnings)
{
var builder = new SqlDdlBuilder();
// Iterate over the container.
foreach (var container in itemCollection.GetItems<EntityContainer>())
{
// Generate create table statements.
foreach (var set in container.BaseEntitySets)
{
// If it is a type of entitySet, generate Create Table statements.
var entitySet = set as EntitySet;
if (entitySet != null)
{
builder.AppendCreateTable(entitySet);
}
}
// Generate Foreign Key constraints.
foreach (var set in container.BaseEntitySets)
{
// If it is association set, generate Foreign Key constraints.
var associationSet = set as AssociationSet;
if (associationSet != null)
{
builder.AppendCreateForeignKeys(associationSet);
}
}
}
// Return the final command text.
return builder.GetCommandText(returnWarnings);
}
示例3: StorageMappingItemCollection
public StorageMappingItemCollection(EdmItemCollection edmCollection, StoreItemCollection storeCollection,
params string[] filePaths)
: base(DataSpace.CSSpace)
{
EntityUtil.CheckArgumentNull(edmCollection, "edmCollection");
EntityUtil.CheckArgumentNull(storeCollection, "storeCollection");
EntityUtil.CheckArgumentNull(filePaths, "filePaths");
this.m_edmCollection = edmCollection;
this.m_storeItemCollection = storeCollection;
// Wrap the file paths in instances of the MetadataArtifactLoader class, which provides
// an abstraction and a uniform interface over a diverse set of metadata artifacts.
//
MetadataArtifactLoader composite = null;
List<XmlReader> readers = null;
try
{
composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(filePaths, XmlConstants.CSSpaceSchemaExtension);
readers = composite.CreateReaders(DataSpace.CSSpace);
this.Init(edmCollection, storeCollection, readers,
composite.GetPaths(DataSpace.CSSpace), true /*throwOnError*/);
}
finally
{
if (readers != null)
{
Helper.DisposeXmlReaders(readers);
}
}
}
示例4: LegacyDbExpressionConverterTests
public LegacyDbExpressionConverterTests()
{
const string ssdl =
"<Schema Namespace='AdventureWorksModel.Store' Provider='System.Data.SqlClient' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'>"
+
" <EntityContainer Name='AdventureWorksModelStoreContainer'>" +
" <EntitySet Name='EntitiesSet' EntityType='AdventureWorksModel.Store.Entities' Schema='dbo' />" +
" <EntitySet Name='OtherEntitiesSet' EntityType='AdventureWorksModel.Store.OtherEntities' Schema='dbo' />" +
" </EntityContainer>" +
" <EntityType Name='Entities'>" +
" <Key>" +
" <PropertyRef Name='Id' />" +
" </Key>" +
" <Property Name='Id' Type='int' StoreGeneratedPattern='Identity' Nullable='false' />" +
" <Property Name='Name' Type='nvarchar(max)' Nullable='false' />" +
" </EntityType>" +
" <EntityType Name='OtherEntities'>" +
" <Key>" +
" <PropertyRef Name='Id' />" +
" </Key>" +
" <Property Name='Id' Type='int' StoreGeneratedPattern='Identity' Nullable='false' />" +
" <Property Name='Name' Type='nvarchar(max)' Nullable='false' />" +
" </EntityType>" +
"</Schema>";
_storeItemCollection = Utils.CreateStoreItemCollection(ssdl);
_legacyStoreItemCollection = _storeItemCollection.ToLegacyStoreItemCollection();
_legacyDbExpressionConverter = new LegacyDbExpressionConverter(_legacyStoreItemCollection);
}
示例5: ToStoreLegacyType_returns_legacy_type_for_EntityType
public void ToStoreLegacyType_returns_legacy_type_for_EntityType()
{
const string ssdl =
"<Schema Namespace='AdventureWorksModel.Store' Provider='System.Data.SqlClient' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'>"
+
" <EntityContainer Name='AdventureWorksModelStoreContainer'>" +
" <EntitySet Name='Entities' EntityType='AdventureWorksModel.Store.Entities' Schema='dbo' />" +
" </EntityContainer>" +
" <EntityType Name='Entities'>" +
" <Key>" +
" <PropertyRef Name='Id' />" +
" </Key>" +
" <Property Name='Id' Type='int' StoreGeneratedPattern='Identity' Nullable='false' />" +
" <Property Name='Name' Type='nvarchar(max)' Nullable='false' />" +
" </EntityType>" +
"</Schema>";
var storeItemCollection = Utils.CreateStoreItemCollection(ssdl);
var legacyStoreItemCollection =
new LegacyMetadata.StoreItemCollection(new[] { XmlReader.Create(new StringReader(ssdl)) });
var entityTypeUsage =
TypeUsage.CreateDefaultTypeUsage(storeItemCollection.GetItem<EntityType>("AdventureWorksModel.Store.Entities"));
var legacyEntityTypeUsage =
entityTypeUsage.ToLegacyStoreTypeUsage(legacyStoreItemCollection.GetItems<LegacyMetadata.EdmType>().ToArray());
TypeUsageVerificationHelper.VerifyTypeUsagesEquivalent(legacyEntityTypeUsage, entityTypeUsage);
}
示例6: GenerateDatabaseScript
public static string GenerateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection)
{
if (storeItemCollection == null)
return string.Empty;
var result = new StringBuilder();
result.Append(string.Join(Environment.NewLine, GenerateTables(storeItemCollection)));
result.AppendLine();
result.Append(string.Join(Environment.NewLine, GenerateForeignKeys(storeItemCollection)));
result.AppendLine();
return result.ToString();
}
示例7: DbDeleteDatabase
/// <summary>
/// API for deleting the database.
/// In SQLCE case, this will translate to File.Delete() call.
/// Note: Timeout and storeItemCollection parameters are ignored.
/// </summary>
/// <param name="connection"></param>
/// <param name="timeOut"></param>
/// <param name="storeItemCollection"></param>
protected override void DbDeleteDatabase(DbConnection connection, int? timeOut, StoreItemCollection storeItemCollection)
{
// Validate that connection is a SqlCeConnection.
ValidateConnection(connection);
// We don't support create/delete database operations inside a transaction as they can't be rolled back.
if (InTransactionScope())
{
throw ADP1.DeleteDatabaseNotAllowedWithinTransaction();
}
// Throw an exception if connection is open.
// We should not close the connection because user could have result sets/data readers associated with this connection.
// Thus, it is users responsiblity to close the connection before calling delete database.
//
if (connection.State
== ConnectionState.Open)
{
throw ADP1.DeleteDatabaseWithOpenConnection();
}
if (_isLocalProvider)
{
CommonUtils.DeleteDatabase(connection.DataSource);
}
else
{
try
{
Type rdpType;
// If we are working with RDP, then we will need to invoke the APIs through reflection.
var engine = RemoteProviderHelper.GetRemoteSqlCeEngine(connection.ConnectionString, out rdpType);
Debug.Assert(engine != null);
// Invoke the required method on SqlCeEngine.
var mi = rdpType.GetMethod("DeleteDatabaseWithError", new[] { typeof(string), typeof(int?) });
Debug.Assert(mi != null);
// We will pass 'timeout' to RDP, this will be used as timeout period for connecting and executing on TDSServer.
mi.Invoke(engine, new object[] { connection.DataSource, timeOut });
}
catch (Exception e)
{
throw e.GetBaseException();
}
}
}
示例8: GenerateForeignKeys
static IEnumerable<string> GenerateForeignKeys(StoreItemCollection storeItems)
{
foreach (var associationSet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<AssociationSet>())
{
var result = new StringBuilder();
ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single<ReferentialConstraint>();
AssociationSetEnd end = associationSet.AssociationSetEnds[constraint.FromRole.Name];
AssociationSetEnd end2 = associationSet.AssociationSetEnds[constraint.ToRole.Name];
result.AppendFormat("ALTER TABLE {0}.{1} ADD FOREIGN KEY ({2}) REFERENCES {3}.{4}({5}){6};",
SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end2.EntitySet)),
SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)),
string.Join(", ", constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name))),
SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end.EntitySet)),
SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)),
string.Join(", ", constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))),
end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? " ON DELETE CASCADE" : string.Empty);
yield return result.ToString();
}
}
示例9: Generate
/// <summary>
/// Main driver function.
/// </summary>
/// <param name="args"></param>
public static void Generate(string outputFileName)
{
//The following functions are omitted because they have counterparts in the BCL
string[] omittedFunctions = new[]
{
"Sum", "Min", "Max", "Average", "Avg",
"Count", "BigCount",
"Trim", "RTrim", "LTrim",
"Concat", "Length", "Substring",
"Replace", "IndexOf", "ToUpper", "ToLower",
"Contains", "StartsWith", "EndsWith", "Year", "Month", "Day",
"DayOfYear", "Hour", "Minute", "Second", "Millisecond", "CurrentDateTime", "CurrentDateTimeOffset",
"CurrentUtcDateTime",
"BitwiseAnd", "BitwiseOr", "BitwiseXor", "BitwiseNot",
"Round", "Abs", "Power", "NewGuid",
"Floor", "Ceiling",
};
//The following functions are omitted from SqlFunctions because they already exist in EntityFunctions
string[] omittedSqlFunctions = new[]
{
"STDEV", "STDEVP", "VAR", "VARP", "COUNT_BIG",
"Left", "Right", "Reverse", "GetTotalOffsetMinutes",
"TruncateTime", "CreateDateTime",
"CreateDateTimeOffset", "CreateTime", "Add", "Diff",
"Truncate", "SYSDATETIME", "SYSUTCDATETIME", "SYSDATETIMEOFFSET",
"LEN", "LOWER", "UPPER", "NEWID",
};
//Generate Sql Server function stubs
String ssdl = @"<Schema Namespace='LinqFunctionStubsGenerator' Alias='Self' Provider='SampleEntityFrameworkProvider' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2006/04/edm/ssdl'></Schema>";
XmlReader[] xmlReaders = new XmlReader[1];
xmlReaders[0] = XmlReader.Create(new StringReader(ssdl));
StoreItemCollection storeItemCollection = new StoreItemCollection(xmlReaders);
IEnumerable<EdmFunction> sqlFunctions = storeItemCollection.GetItems<EdmFunction>()
.Where(f => f.NamespaceName == "SqlServer")
.Where(f => !(omittedFunctions.Concat(omittedSqlFunctions)).Contains(f.Name, StringComparer.OrdinalIgnoreCase));
FunctionStubFileWriter sqlStubsFileWriter = new FunctionStubFileWriter(sqlFunctions, GetFunctionNamingDictionary(), GetParameterNamingDictionary());
sqlStubsFileWriter.GenerateToFile(outputFileName, "SampleEntityFrameworkProvider", "SampleSqlFunctions", "SqlServer", true);
}
示例10: EntityModelSchemaGenerator
public EntityModelSchemaGenerator(StoreItemCollection storeItemCollection, string namespaceName, string modelEntityContainerName)
{
EDesignUtil.CheckArgumentNull(storeItemCollection, "storeItemCollection");
EDesignUtil.CheckArgumentNull(namespaceName, "namespaceName");
EDesignUtil.CheckArgumentNull(modelEntityContainerName, "modelEntityContainerName");
var storeContainers = storeItemCollection.GetItems<EntityContainer>().ToArray();
if (storeContainers.Length != 1)
{
throw EDesignUtil.SingleStoreEntityContainerExpected("storeItemCollection");
}
Initialize(
storeContainers[0],
storeItemCollection.GetItems<EdmFunction>().Where(f => f.IsFromProviderManifest == false &&
f.IsComposableAttribute == true &&
f.AggregateAttribute == false),
namespaceName,
modelEntityContainerName);
}
示例11: DbDatabaseExists
protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
{
if (connection == null)
throw new ArgumentNullException("connection");
MySqlConnection conn = connection as MySqlConnection;
if (conn == null)
throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection");
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.ConnectionString = conn.ConnectionString;
string dbName = builder.Database;
builder.Database = "mysql";
using (MySqlConnection c = new MySqlConnection(builder.ConnectionString))
{
c.Open();
DataTable table = c.GetSchema("Databases", new string[] { dbName });
if (table != null && table.Rows.Count == 1) return true;
return false;
}
}
示例12: GenerateTables
static IEnumerable<string> GenerateTables(StoreItemCollection storeItems)
{
foreach (var entitySet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<EntitySet>())
{
var result = new StringBuilder();
var tableName = MetadataHelpers.GetTableName(entitySet);
var schemaName = MetadataHelpers.GetSchemaName(entitySet);
result.AppendFormat("CREATE TABLE {0}.{1} (", SqlGenerator.QuoteIdentifier(schemaName), SqlGenerator.QuoteIdentifier(tableName));
result.AppendLine();
result.Append("\t");
result.Append(string.Join("," + Environment.NewLine + "\t", MetadataHelpers.GetProperties(entitySet.ElementType).Select(p => GenerateColumn(p))));
result.Append(");");
result.AppendLine();
result.AppendFormat("ALTER TABLE {0}.{1} ADD PRIMARY KEY ({2});",
SqlGenerator.QuoteIdentifier(schemaName),
SqlGenerator.QuoteIdentifier(tableName),
string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
result.AppendLine();
yield return result.ToString();
}
}
示例13: DbDeleteDatabase
protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
{
if (connection == null)
throw new ArgumentNullException("connection");
MySqlConnection conn = connection as MySqlConnection;
if (conn == null)
throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection");
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.ConnectionString = conn.ConnectionString;
string dbName = builder.Database;
builder.Database = "mysql";
using (MySqlConnection c = new MySqlConnection(builder.ConnectionString))
{
c.Open();
MySqlCommand cmd = new MySqlCommand(String.Format("DROP DATABASE IF EXISTS `{0}`", dbName), c);
if (commandTimeout.HasValue)
cmd.CommandTimeout = commandTimeout.Value;
cmd.ExecuteNonQuery();
}
}
示例14: DbCreateDatabase
protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
{
if (connection == null)
throw new ArgumentNullException("connection");
MySqlConnection conn = connection as MySqlConnection;
if (conn == null)
throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection");
string query = DbCreateDatabaseScript(null, storeItemCollection);
using (MySqlConnection c = new MySqlConnection())
{
MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(conn.ConnectionString);
string dbName = sb.Database;
sb.Database = "mysql";
c.ConnectionString = sb.ConnectionString;
c.Open();
string fullQuery = String.Format("CREATE DATABASE `{0}`; USE `{0}`; {1}", dbName, query);
MySqlScript s = new MySqlScript(c, fullQuery);
s.Execute();
}
}
示例15: ToStorageMappingItemCollection
private static StorageMappingItemCollection ToStorageMappingItemCollection(
this DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection,
StoreItemCollection storeItemCollection)
{
//Contract.Requires(databaseMapping != null);
//Contract.Requires(itemCollection != null);
//Contract.Requires(storeItemCollection != null);
var stringBuilder = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(
stringBuilder, new XmlWriterSettings
{
Indent = true
}))
{
new MslSerializer().Serialize(databaseMapping, xmlWriter);
}
using (var xmlReader = XmlReader.Create(new StringReader(stringBuilder.ToString())))
{
return new StorageMappingItemCollection(itemCollection, storeItemCollection, new[] { xmlReader });
}
}