public EntityStoreSchemaGeneratorDatabaseSchemaLoader(EntityConnection entityConnection, Version storeSchemaModelVersion) { Debug.Assert(entityConnection != null, "entityConnection != null"); Debug.Assert(entityConnection.State == ConnectionState.Closed, "expected closed connection"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(storeSchemaModelVersion), "invalid version"); _connection = entityConnection; _storeSchemaModelVersion = storeSchemaModelVersion; }
public void GetInitialModelContents_returns_contents() { foreach (var targetSchemaVersion in EntityFrameworkVersion.GetAllVersions()) { Assert.Equal( EdmUtils.CreateEdmxString(targetSchemaVersion, string.Empty, string.Empty, string.Empty), new InitialModelContentsFactory().GetInitialModelContents(targetSchemaVersion)); } }
/// <summary> /// Return the FeatureState for the GenerateUpdateViews feature /// </summary> internal static FeatureState GetGenerateUpdateViewsFeatureState(Version schemaVersion) { Debug.Assert(EntityFrameworkVersion.IsValidVersion(schemaVersion), "Invalid schema version."); // This attribute was added in v2 to support Reporting Services return(schemaVersion > EntityFrameworkVersion.Version1 ? FeatureState.VisibleAndEnabled : FeatureState.VisibleButDisabled); }
public LegacyCodeGenerationDriver(LanguageOption language, Version targetEntityFrameworkVersion) { Debug.Assert( EntityFrameworkVersion.IsValidVersion(targetEntityFrameworkVersion), "invalid targetEntityFrameworkVersion"); _language = language; _targetEntityFrameworkVersion = targetEntityFrameworkVersion; }
public static CodeGeneratorBase Create(LanguageOption language, Version targetEntityFrameworkVersion) { Debug.Assert( EntityFrameworkVersion.IsValidVersion(targetEntityFrameworkVersion), "invalid targetEntityFrameworkVersion"); return(targetEntityFrameworkVersion == EntityFrameworkVersion.Version1 ? (CodeGeneratorBase) new EntityClassGenerator(language) : new EntityCodeGenerator(language, targetEntityFrameworkVersion)); }
public void FunctionImportColumnInformation_always_enabled() { foreach (var targetSchemaVersion in EntityFrameworkVersion.GetAllVersions()) { Assert.Equal( FeatureState.VisibleAndEnabled, IsFeatureEnabledForArtifact( targetSchemaVersion, EdmFeatureManager.GetFunctionImportColumnInformationFeatureState)); } }
protected override void InitializeModelContents(Version targetSchemaVersion) { Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion)); Debug.Assert(_model == null, "overwriting already initialized edmx???"); _model = XDocument.Parse( _initialModelContentsFactory.GetInitialModelContents(targetSchemaVersion)); Debug.Assert( SchemaManager.GetSchemaVersion(_model.Root.Name.Namespace) == targetSchemaVersion, "Schema version should not change or we should not cache the document"); }
internal static HashSet <string> InitializeExistingNamespaces(Project project) { var existingNamespaces = new HashSet <string>(); if (project != null) { // find the namespace used in the CSDL section of each existing edmx file in the project var vsHierarchy = VsUtils.GetVsHierarchy(project, Services.ServiceProvider); var fileFinder = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx); fileFinder.FindInProject(vsHierarchy); foreach (var fileInfo in fileFinder.MatchingFiles) { try { var xmlDocument = EdmUtils.SafeLoadXmlFromPath(fileInfo.Path); foreach (var schemaVersion in EntityFrameworkVersion.GetAllVersions()) { var nsMgr = SchemaManager.GetEdmxNamespaceManager(xmlDocument.NameTable, schemaVersion); foreach ( XmlElement e in xmlDocument.SelectNodes("/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/csdl:Schema", nsMgr)) { var namespaceValue = e.GetAttribute("Namespace"); if (!string.IsNullOrEmpty(namespaceValue)) { existingNamespaces.Add(namespaceValue); } } } } // swallow various exceptions that come from reading the file or parsing xml // We just skip this document in the event of an exception. catch (IOException) { } catch (UnauthorizedAccessException) { } catch (NotSupportedException) { } catch (SecurityException) { } catch (XmlException) { } } } return(existingNamespaces); }
public static EdmItemCollection CreateAndValidateEdmItemCollection(string csdl, Version targetFrameworkVersion) { if (csdl == null) { throw new ArgumentNullException("csdl"); } if (targetFrameworkVersion == null) { throw new ArgumentNullException("targetFrameworkVersion"); } if (!EntityFrameworkVersion.IsValidVersion(targetFrameworkVersion)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.ErrorNonValidTargetVersion, targetFrameworkVersion), "targetFrameworkVersion"); } IList <EdmSchemaError> schemaErrors; EdmItemCollection edmItemCollection; using (var textReader = new StringReader(csdl)) { using (var xmlReader = XmlReader.Create(textReader)) { edmItemCollection = EdmItemCollection.Create(new[] { xmlReader }, null, out schemaErrors); } } if (schemaErrors.Count > 0) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Resources.ErrorCsdlNotValid, string.Join(Environment.NewLine, schemaErrors.Select(e => e.Message)))); } if (edmItemCollection.CsdlVersion() > targetFrameworkVersion) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Resources.TargetVersionSchemaVersionMismatch, edmItemCollection.CsdlVersion(), targetFrameworkVersion)); } return(edmItemCollection); }
public void CopyToSSDL_false_causes_CopyExtendedPropertiesToSsdlElement_to_not_copy_property() { foreach (var version in EntityFrameworkVersion.GetAllVersions()) { var csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL = CreateEntityTypeWithExtendedProperty( SchemaManager.GetEDMXNamespaceName(EntityFrameworkVersion.Version1), "false"); var ssdlEntityTypeElement = new XElement( (XNamespace)(SchemaManager.GetSSDLNamespaceName(EntityFrameworkVersion.Version1)) + "EntityType", new XAttribute("Name", "TestEntityType")); OutputGeneratorHelpers.CopyExtendedPropertiesToSsdlElement( csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL, ssdlEntityTypeElement); Assert.Empty(ssdlEntityTypeElement.Elements()); } }
public void GetAllPrimitiveTypes_returns_all_primitive_types_for_version() { foreach (var schemaVersion in EntityFrameworkVersion.GetAllVersions()) { // remove geo spatial types for schema versions V1 and V2 var expectedTypes = PrimitiveType .GetEdmPrimitiveTypes() .Where(t => schemaVersion == EntityFrameworkVersion.Version3 || !IsGeoSpatialType(t)) .Select(t => t.Name); Assert.Equal(expectedTypes, ModelHelper.AllPrimitiveTypes(schemaVersion)); } }
private static MetadataWorkspace GetProviderSchemaMetadataWorkspace( IDbDependencyResolver resolver, string providerInvariantName, SystemDataCommon.DbConnection providerConnection, Version targetSchemaVersion) { Debug.Assert(resolver != null, "resolver != null"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty"); Debug.Assert(providerConnection != null, "providerConnection != null"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid targetSchemaVersion"); string csdlName; string ssdlName; string mslName; if (targetSchemaVersion >= EntityFrameworkVersion.Version3) { csdlName = DbProviderManifest.ConceptualSchemaDefinitionVersion3; ssdlName = DbProviderManifest.StoreSchemaDefinitionVersion3; mslName = DbProviderManifest.StoreSchemaMappingVersion3; } else { csdlName = DbProviderManifest.ConceptualSchemaDefinition; ssdlName = DbProviderManifest.StoreSchemaDefinition; mslName = DbProviderManifest.StoreSchemaMapping; } var providerServices = resolver.GetService <DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "Trying to get unregistered provider."); var providerManifest = providerServices.GetProviderManifest( providerServices.GetProviderManifestToken(providerConnection)); var edmItemCollection = LoadEdmItemCollection(csdlName); var storeItemCollection = LoadStoreItemCollection(providerManifest, ssdlName); var mappingItemCollection = LoadMappingItemCollection(providerManifest, mslName, edmItemCollection, storeItemCollection); var workspace = new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => mappingItemCollection); // TODO: there is currently no public surface to do this (workitem 606 on codeplex) //// make the views generate here so we can wrap the provider schema problems //// in a ProviderIncompatibleException //ForceViewGeneration(workspace); return(workspace); }
public void LoadFunctionReturnTableDetails_not_invoked_for_pre_V3_target_schema() { var mockEntityConnection = new Mock <EntityConnection>(); foreach (var version in EntityFrameworkVersion.GetAllVersions()) { var mockLoader = new Mock <EntityStoreSchemaGeneratorDatabaseSchemaLoader>( mockEntityConnection.Object, version) { CallBase = true }; mockLoader.Setup(l => l.LoadTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >())) .Returns(Enumerable.Empty <TableDetailsRow>()); mockLoader.Setup(l => l.LoadViewDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >())) .Returns(Enumerable.Empty <TableDetailsRow>()); mockLoader.Setup(l => l.LoadRelationships(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >())) .Returns(Enumerable.Empty <RelationshipDetailsRow>()); mockLoader.Setup(l => l.LoadFunctionDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >())) .Returns(Enumerable.Empty <FunctionDetailsRowView>()); mockLoader.Setup( l => l.LoadFunctionReturnTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >())) .Returns(Enumerable.Empty <TableDetailsRow>()); mockLoader.Object.LoadStoreSchemaDetails(new List <EntityStoreSchemaFilterEntry>()); mockLoader.Verify( l => l.LoadTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()), Times.Once()); mockLoader.Verify( l => l.LoadViewDetails(It.IsAny <IList <EntityStoreSchemaFilterEntry> >()), Times.Once()); mockLoader.Verify( l => l.LoadRelationships(It.IsAny <IList <EntityStoreSchemaFilterEntry> >()), Times.Once()); mockLoader.Verify( l => l.LoadFunctionDetails(It.IsAny <IList <EntityStoreSchemaFilterEntry> >()), Times.Once()); mockLoader.Verify( l => l.LoadFunctionReturnTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()), version == EntityFrameworkVersion.Version3 ? Times.Once() : Times.Never()); } }
public void CopyToSSDL_true_causes_CopyExtendedPropertiesToSsdlElement_to_copy_property() { foreach (var version in EntityFrameworkVersion.GetAllVersions()) { var csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL = CreateEntityTypeWithExtendedProperty( SchemaManager.GetEDMXNamespaceName(version), "true"); var ssdlEntityTypeElement = new XElement( (XNamespace)(SchemaManager.GetSSDLNamespaceName(version)) + "EntityType", new XAttribute("Name", "TestEntityType")); OutputGeneratorHelpers.CopyExtendedPropertiesToSsdlElement( csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL, ssdlEntityTypeElement); Assert.Equal( "<MyProp p1:MyAttribute=\"MyValue\" xmlns:p1=\"http://myExtendedProperties\" xmlns=\"http://myExtendedProperties\" />", ssdlEntityTypeElement.Elements().First().ToString()); } }
// <summary> // Whether the given <paramref name="schemaVersion" /> is the latest version supported by the given // Entity Framework (i.e. EntityFramework.dll or System.Data.Entity.dll) <paramref name="assemblyVersion" /> // </summary> // <param name="schemaVersion">Version of the EF schema.</param> // <param name="assemblyVersion"> // Version of an Entity Framework (i.e. EntityFramework.dll or System.Data.Entity.dll) assembly. // </param> // <param name="targetNetFrameworkVersion"> // Targeted .NET Framework version. Used to distinguish EF5 from EF4 if the assembly version if 4.0.0.0. // </param> // <returns> // <c>True</c> if the given <paramref name="schemaVersion" /> is the latest version supported by the given // Entity Framework (i.e. EntityFramework.dll or System.Data.Entity.dll) <paramref name="assemblyVersion" />. // <c>False</c> otherwise. // </returns> public static bool IsSchemaVersionLatestForAssemblyVersion( Version schemaVersion, Version assemblyVersion, Version targetNetFrameworkVersion) { Debug.Assert(EntityFrameworkVersion.IsValidVersion(schemaVersion), "Invalid schema version"); Debug.Assert(assemblyVersion != null, "assemblyVersion != null"); if (assemblyVersion == Version4 && targetNetFrameworkVersion >= NetFrameworkVersioningHelper.NetFrameworkVersion4_5) { assemblyVersion = Version5Net45; } return ((schemaVersion == EntityFrameworkVersion.Version3 && assemblyVersion >= Version5Net45) || (schemaVersion == EntityFrameworkVersion.Version2 && (assemblyVersion >= Version4 && assemblyVersion <= Version5Net40)) || (schemaVersion == EntityFrameworkVersion.Version1 && assemblyVersion == Version1)); }
private AssociationType GenerateAssociationType( SimpleMappingContext mappingContext, AssociationType storeAssociationType, UniqueIdentifierService globallyUniqueTypeNames) { Debug.Assert(storeAssociationType.RelationshipEndMembers.Count == 2); var storeEndMember0 = (AssociationEndMember)storeAssociationType.RelationshipEndMembers[0]; var storeEndMember1 = (AssociationEndMember)storeAssociationType.RelationshipEndMembers[1]; var storeSchemaVersion = EntityFrameworkVersion.DoubleToVersion(mappingContext.StoreModel.SchemaVersion); var isFkAssociation = storeSchemaVersion > EntityFrameworkVersion.Version1 && (_generateForeignKeyProperties || RequiresReferentialConstraint(storeAssociationType)); var uniqueEndMemberNames = new UniqueIdentifierService(StringComparer.OrdinalIgnoreCase); var multiplicityOverride = GetMultiplicityOverride(storeAssociationType); var conceptualEndMember0 = GenerateAssociationEndMember( mappingContext, storeEndMember0, uniqueEndMemberNames, multiplicityOverride); var conceptualEndMember1 = GenerateAssociationEndMember( mappingContext, storeEndMember1, uniqueEndMemberNames, multiplicityOverride); var conceptualAssociationType = AssociationType.Create( CreateModelName(storeAssociationType.Name, globallyUniqueTypeNames), _namespaceName, isFkAssociation, DataSpace.CSpace, conceptualEndMember0, conceptualEndMember1, CreateReferentialConstraint(mappingContext, storeAssociationType), null); CreateModelNavigationProperties(conceptualAssociationType); mappingContext.AddMapping(storeAssociationType, conceptualAssociationType); return(conceptualAssociationType); }
/// <summary> /// Creates an EntityConnection loaded with the providers metadata for the store schema. /// </summary> /// <param name="resolver">Resolver used to resolve provider services.</param> /// <param name="providerInvariantName">The provider invariant name.</param> /// <param name="connectionString">The connection for the providers connection.</param> /// <param name="targetSchemaVersion">The target Entity Framework schema version that is being targeted.</param> /// <returns>An EntityConnection that can query the ConceptualSchemaDefinition for the provider.</returns> /// <remarks>virtual for testing</remarks> public virtual EntityConnection Create( IDbDependencyResolver resolver, string providerInvariantName, string connectionString, Version targetSchemaVersion) { Debug.Assert(resolver != null, "resolver != null"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty"); Debug.Assert(!string.IsNullOrWhiteSpace(connectionString), "connectionString cannot be null or empty"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid targetSchemaVersion"); SystemDataCommon.DbProviderFactory factory; try { factory = SystemDataCommon.DbProviderFactories.GetFactory(providerInvariantName); } catch (ArgumentException e) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources_VersioningFacade.EntityClient_InvalidStoreProvider, providerInvariantName), e); } var providerConnection = factory.CreateConnection(); if (providerConnection == null) { throw new ProviderIncompatibleException( String.Format( CultureInfo.CurrentCulture, Resources_VersioningFacade.ProviderFactoryReturnedNullFactory, providerInvariantName)); } providerConnection.ConnectionString = connectionString; return(new EntityConnection( GetProviderSchemaMetadataWorkspace( resolver, providerInvariantName, providerConnection, targetSchemaVersion), providerConnection)); }
/// <summary> /// Creates an EntityConnection loaded with the providers metadata for the latest available store schema. /// Note that the targetEntityFrameworkVersion parameter uses internal EntityFramework version numbers as /// described in the <see cref="EntityFrameworkVersion" /> class. /// </summary> /// <param name="resolver">Resolver used to resolve provider services.</param> /// <param name="providerInvariantName">The provider invariant name.</param> /// <param name="connectionString">The connection for the providers connection.</param> /// <param name="maxAllowedSchemaVersion">The maximum allowed Entity Framework schema version that is being targeted.</param> /// <param name="storeSchemaModelVersion"> /// The version of the store schema model supported by the provider. Can be either v1 or v3 (store schema model in v2 did not change /// from v1, in v3 TVFs are supported and the provider needs to know how to handle Esql queries that ask for TVFs). /// Note that schema view artifacts themselves are v1 since there is nothing that is needed to ask for v3 concepts that /// cannot be expressed in v1 terms. /// **This value MUST NOT be used as the version of the model that will be created for the user (which can be /// any version regardless of this value), nor as the version of schema view artifacts (which is always v1) /// but rather it is a version of concepts we are asking the provider to return details for (to put it simply if this is v3 /// we will ask the provider about TVFs, otherwise this is v1 and we don't ask about TVFs)** /// </param> /// <returns>An EntityConnection that can query the ConceptualSchemaDefinition for the provider.</returns> /// <remarks>virtual for testing</remarks> public virtual EntityConnection Create( IDbDependencyResolver resolver, string providerInvariantName, string connectionString, Version maxAllowedSchemaVersion, out Version storeSchemaModelVersion) { Debug.Assert(resolver != null, "resolver != null"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty"); Debug.Assert(!string.IsNullOrWhiteSpace(connectionString), "connectionString cannot be null or empty"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(maxAllowedSchemaVersion), "invalid maxAllowedSchemaVersion"); // We are going to try loading all versions of the store schema model starting from the newest. // The first version of the model that was shipped with EntityFrameworkVersions.Version1 and EntityFrameworkVersions.Version2 is the last one // we try, if it fails to load let the exception to propagate up to the caller. var versions = EntityFrameworkVersion .GetAllVersions() .Where(v => v > EntityFrameworkVersion.Version2 && v <= maxAllowedSchemaVersion) .OrderByDescending(v => v); foreach (var version in versions) { try { storeSchemaModelVersion = version; return (Create( resolver, providerInvariantName, connectionString, storeSchemaModelVersion)); } catch (Exception e) { // Ignore the exception with the current version and try the next one. if (!IsCatchableExceptionType(e)) { throw; } } } storeSchemaModelVersion = EntityFrameworkVersion.Version1; return(Create(resolver, providerInvariantName, connectionString, storeSchemaModelVersion)); }
// internal for testing internal IEnumerable <EdmFunction> GenerateFunctions( SimpleMappingContext mappingContext, EdmModel storeModel, UniqueIdentifierService uniqueEntityContainerNames, UniqueIdentifierService globallyUniqueTypeNames) { Debug.Assert(mappingContext != null, "mappingContext != null"); Debug.Assert(storeModel != null, "storeModel != null"); Debug.Assert(uniqueEntityContainerNames != null, "uniqueEntityContainerNames != null"); Debug.Assert(globallyUniqueTypeNames != null, "globallyUniqueTypeNames != null"); // TODO: Note we import only TVFs here and other store functions are // imported elsewhere - ideally we import all functions in one place // http://entityframework.codeplex.com/workitem/925 if (EntityFrameworkVersion.DoubleToVersion(storeModel.SchemaVersion) < EntityFrameworkVersion.Version3) { yield break; } foreach (var storeFunction in storeModel.Functions) { if (storeFunction.IsComposableAttribute && !storeFunction.AggregateAttribute && storeFunction.Parameters.All(p => p.Mode == ParameterMode.In)) { var functionImport = GenerateFunction( mappingContext, storeFunction, uniqueEntityContainerNames, globallyUniqueTypeNames); if (functionImport != null) { mappingContext.AddMapping(storeFunction, functionImport); yield return(functionImport); } } } }
protected internal override bool ExpectEFObjectForXObject(XObject xobject) { var xe = xobject as XElement; if (xe != null) { foreach (var n in SchemaManager.GetEDMXNamespaceNames()) { // see if this element is the "Edmx" element. We don't exepct a EFObject for this element if (xe.Name.NamespaceName.Equals(n, StringComparison.OrdinalIgnoreCase)) { if (xe.Name.LocalName.Equals("Edmx", StringComparison.OrdinalIgnoreCase)) { return(false); } } } // now look for items that are in the EF set of namespaces (ie, csdl/ssdl/msl/edmx namespaces. // If something isn't in this namespace, we return false below (since it won't have a model element) // if something is in this namespace, we'll base this to the base class, which will return true. // // the reason this is here is there will be asserts after undo/redo operations if we can't find // a model element for the xnode that is part of the undo/redo. Returning false from this method // tells us not to expect the model element. // foreach (var v in EntityFrameworkVersion.GetAllVersions()) { foreach (var s in SchemaManager.GetAllNamespacesForVersion(v)) { if (xe.Name.NamespaceName.Equals(s, StringComparison.OrdinalIgnoreCase)) { // we only expect EFObjects for items in the Entity Framework namespaces return(base.ExpectEFObjectForXObject(xobject)); } } } } return(false); }
public string GetInitialModelContents(Version targetSchemaVersion) { Debug.Assert( EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid schema version"); if (_initialModelContents == null) { AddSchemaSpecificReplacements(_replacementsDictionary, targetSchemaVersion); var sb = new StringBuilder(_fileContentsTemplate); foreach (var pair in _replacementsDictionary) { sb.Replace(pair.Key, pair.Value); } _initialModelContents = sb.ToString(); } return(_initialModelContents); }
public void RetargetWithMetadataConverter_does_not_modify_xml_if_converter_returns_null() { foreach (var schemaVersion in EntityFrameworkVersion.GetAllVersions()) { var model = new XDocument(new XElement("root")); model.Changed += (sender, args) => { throw new InvalidOperationException("Unexpected changes to model."); }; var mockConverter = new Mock <MetadataConverterDriver>(); mockConverter .Setup(c => c.Convert(It.IsAny <XmlDocument>(), It.IsAny <Version>())) .Returns( (XmlDocument doc, Version version) => { Assert.Same(schemaVersion, version); return(null); }); RetargetXmlNamespaceCommand.RetargetWithMetadataConverter(model, schemaVersion, mockConverter.Object); } }
public static LegacyMetadata.MetadataWorkspace ToLegacyMetadataWorkspace(this MetadataWorkspace metadataWorkspace) { Debug.Assert(metadataWorkspace != null, "metadataWorkspace != null"); // The cloned workspace is supposed to be used only by provider. Therefore we only care about SSpace. // For CSpace and C-S mapping we register dummy item collections just to make the workspace checks pass. var legacyStoreItemCollection = ((StoreItemCollection)metadataWorkspace.GetItemCollection(DataSpace.SSpace)).ToLegacyStoreItemCollection(); var version = EntityFrameworkVersion.DoubleToVersion(legacyStoreItemCollection.StoreSchemaVersion); var legacyEdmItemCollection = GetLegacyEdmItemCollection(version); var legacyWorkspace = new LegacyMetadata.MetadataWorkspace(); legacyWorkspace.RegisterItemCollection(legacyEdmItemCollection); legacyWorkspace.RegisterItemCollection(legacyStoreItemCollection); var msl = string.Format( CultureInfo.InvariantCulture, MslTemplate, SchemaManager.GetMSLNamespaceName(version), legacyStoreItemCollection.GetItems <LegacyMetadata.EntityContainer>().Single().Name); using (var stringReader = new StringReader(msl)) { using (var reader = XmlReader.Create(stringReader)) { var legacyMappingItemCollection = new LegacyMapping.StorageMappingItemCollection( legacyEdmItemCollection, legacyStoreItemCollection, new[] { reader }); legacyWorkspace.RegisterItemCollection(legacyMappingItemCollection); } } return(legacyWorkspace); }
public SimpleMappingContext Build(EdmModel storeModel) { Debug.Assert(storeModel != null, "storeModel != null"); var mappingContext = new SimpleMappingContext(storeModel, _generateForeignKeyProperties); var uniqueEntityContainerNames = new UniqueIdentifierService(); var globallyUniqueTypeNames = new UniqueIdentifierService(); CollectForeignKeyProperties(mappingContext, storeModel); foreach (var storeEntitySet in storeModel.Containers.Single().EntitySets) { GenerateEntitySet(mappingContext, storeEntitySet, uniqueEntityContainerNames, globallyUniqueTypeNames); } GenerateAssociationSets( mappingContext, uniqueEntityContainerNames, globallyUniqueTypeNames); var functionImports = GenerateFunctions(mappingContext, storeModel, uniqueEntityContainerNames, globallyUniqueTypeNames) .ToArray(); var conceptualModelContainer = EntityContainer.Create( _containerName, DataSpace.CSpace, mappingContext.ConceptualEntitySets() .Concat(mappingContext.ConceptualAssociationSets().Cast <EntitySetBase>()), functionImports, EntityFrameworkVersion.DoubleToVersion(storeModel.SchemaVersion) >= EntityFrameworkVersion.Version2 ? new[] { CreateAnnotationMetadataProperty("LazyLoadingEnabled", "true") } : null); mappingContext.AddMapping(storeModel.Containers.Single(), conceptualModelContainer); return(mappingContext); }
public EntityStoreSchemaGeneratorDatabaseSchemaLoader( EntityConnection entityConnection, Version storeSchemaModelVersion) { Debug.Assert(entityConnection != null, "entityConnection != null"); Debug.Assert(entityConnection.State == ConnectionState.Closed, "expected closed connection"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(storeSchemaModelVersion), "invalid version"); _connection = entityConnection; _storeSchemaModelVersion = storeSchemaModelVersion; if (_connection != null && _connection.StoreConnection != null && string.Equals( _connection.StoreConnection.GetProviderInvariantName(), SqlServerInvariantName, StringComparison.Ordinal) && !SwitchOffMetadataMergeJoins()) { _addOptionMergeJoinInterceptor = new AddOptionMergeJoinInterceptor(); } }
private bool VerifyUserEdit(XName xn) { if (_namespaces == null) { _namespaces = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var v in EntityFrameworkVersion.GetAllVersions()) { foreach (var s in SchemaManager.GetAllNamespacesForVersion(v)) { _namespaces.Add(s); } } } if (_namespaces.Contains(xn.NamespaceName)) { return(false); } else { return(true); } }
/// <remarks>Internal for testing.</remarks> internal static void RetargetWithMetadataConverter(XDocument xdoc, Version targetSchemaVersion, MetadataConverterDriver converter) { Debug.Assert(xdoc != null, "xdoc != null"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid target schema version"); var inputXml = new XmlDocument { PreserveWhitespace = true }; using (var reader = xdoc.CreateReader()) { inputXml.Load(reader); } var outputXml = converter.Convert(inputXml, targetSchemaVersion); if (outputXml != null) { // Dev10 Bug 550594: There is a bug in XmlEditor that prevents from deleting the root node // unless the root node has previous sibling (like a comment or Xml declaration). if (xdoc.Root.PreviousNode == null) { xdoc.Root.AddBeforeSelf(new XComment("")); } // update xml document with new root element xdoc.Root.Remove(); using (var reader = new XmlNodeReader(outputXml)) { var newDoc = XDocument.Load(reader); xdoc.Add(newDoc.Root); } // Do not reload artifact here // Until the transaction is committed, the XLinq representation of the parsed xml tree hasn't been generated yet. } }
public void Create_creates_valid_EntityConnection() { var mockProviderServices = SetupMockProviderServices(); mockProviderServices .Protected() .Setup <DbProviderManifest>("GetDbProviderManifest", ItExpr.IsAny <string>()) .Returns(SqlProviderServices.Instance.GetProviderManifest("2008")); var mockResolver = SetupMockResolver(mockProviderServices); foreach (var efVersion in EntityFrameworkVersion.GetAllVersions()) { var entityConnection = new StoreSchemaConnectionFactory() .Create( mockResolver.Object, "System.Data.SqlClient", "Server=test", efVersion); Assert.NotNull(entityConnection); } }
public EntityStoreSchemaGeneratorDatabaseSchemaLoader( EntityConnection entityConnection, Version storeSchemaModelVersion) { Debug.Assert(entityConnection != null, "entityConnection != null"); Debug.Assert(entityConnection.State == ConnectionState.Closed, "expected closed connection"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(storeSchemaModelVersion), "invalid version"); _connection = entityConnection; _storeSchemaModelVersion = storeSchemaModelVersion; var isSqlServer = false; try { if (_connection != null && _connection.StoreConnection != null && string.Equals( _connection.StoreConnection.GetProviderInvariantName(), SqlServerInvariantName, StringComparison.Ordinal)) { isSqlServer = true; } } catch (Exception) { // Several exceptions can be thrown from GetProviderInvariantName(). // Assume that the provider is not SqlServer unless we can confirm it is. } if (isSqlServer && !SwitchOffMetadataMergeJoins()) { _addOptionMergeJoinInterceptor = new AddOptionMergeJoinInterceptor(); } }
public EdmxEntityProvider(string fileName, EntityFrameworkVersion version = EntityFrameworkVersion.v6) { _fileName = fileName; XMLNamespaceFactory.Version = (byte)version; }
internal static MetadataWorkspace CreateTransientMetadataWorkspace( IList <EntitySet> sourceEntitySets, Version targetEntityFrameworkVersion, string providerInvariantName, string providerManifestToken, DbProviderManifest providerManifest) { Debug.Assert(sourceEntitySets != null, "sourceEntitySets != null"); Debug.Assert(targetEntityFrameworkVersion != null, "targetEntityFrameworkVersion != null"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "invalid providerInvariantName"); Debug.Assert(!string.IsNullOrWhiteSpace(providerManifestToken), "invalid providerManifestToken"); Debug.Assert(providerManifest != null, "providerManifest != null"); var targetDoubleEntityFrameworkVersion = EntityFrameworkVersion.VersionToDouble(targetEntityFrameworkVersion); var storeModel = EdmModel.CreateStoreModel( EntityContainer.Create( StoreContainerName, DataSpace.SSpace, sourceEntitySets, Enumerable.Empty <EdmFunction>(), null), new DbProviderInfo(providerInvariantName, providerManifestToken), providerManifest, targetDoubleEntityFrameworkVersion); foreach (var entityType in sourceEntitySets.Select(e => e.ElementType)) { storeModel.AddItem(entityType); } var storeItemCollection = new StoreItemCollection(storeModel); var edmItemCollection = new EdmItemCollection( EdmModel.CreateConceptualModel( EntityContainer.Create( ModelContainerName, DataSpace.CSpace, Enumerable.Empty <EntitySet>(), Enumerable.Empty <EdmFunction>(), null), targetDoubleEntityFrameworkVersion)); var msl = string.Format( CultureInfo.InvariantCulture, MslTemplate, SchemaManager.GetMSLNamespaceName(targetEntityFrameworkVersion)); StorageMappingItemCollection mappingItemCollection; using (var stringReader = new StringReader(msl)) { using (var reader = XmlReader.Create(stringReader)) { mappingItemCollection = new StorageMappingItemCollection(edmItemCollection, storeItemCollection, new[] { reader }); } } return(new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => mappingItemCollection)); }