Exemple #1
0
        public void Should_be_able_to_roundtrip_model_through_gzip()
        {
            var modelBuilder = new DbModelBuilder();

            modelBuilder.Entity <MigrationsCustomer>();

            var model = modelBuilder.Build(new DbProviderInfo(DbProviders.Sql, "2008"));

            var edmxString = new StringBuilder();

            using (var xmlWriter = XmlWriter.Create(
                       edmxString, new XmlWriterSettings
            {
                Indent = true
            }))
            {
                EdmxWriter.WriteEdmx(model, xmlWriter);
            }

            var modelCompressor = new ModelCompressor();

            var bytes = modelCompressor.Compress(model.GetModel());

            Assert.True(bytes.Length > 2000);

            var edmxXDocument = modelCompressor.Decompress(bytes);

            using (var stringWriter = new StringWriter())
            {
                edmxXDocument.Save(stringWriter);

                Assert.Equal(edmxString.ToString(), stringWriter.ToString());
            }
        }
        private static MetadataWorkspace CreateEdmxBasedWorkspace(DbContext context)
        {
            var edmxBuilder = new StringBuilder();

            EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilder));
            var edmx = XDocument.Parse(edmxBuilder.ToString());

            var edmItemCollection = new EdmItemCollection(
                new[]
            {
                edmx.Descendants(XName.Get("Schema", "http://schemas.microsoft.com/ado/2009/11/edm")).Single().CreateReader()
            });

            var storeItemCollection = new StoreItemCollection(
                new[]
            {
                edmx.Descendants(XName.Get("Schema", "http://schemas.microsoft.com/ado/2009/11/edm/ssdl")).Single().CreateReader()
            });

            var mapping = new StorageMappingItemCollection(
                edmItemCollection,
                storeItemCollection,
                new[]
            {
                new XElement(edmx.Descendants(XName.Get("Mapping", "http://schemas.microsoft.com/ado/2009/11/mapping/cs")).Single())
                .CreateReader()
            });

            return(new MetadataWorkspace(() => edmItemCollection, () => storeItemCollection, () => mapping));
        }
Exemple #3
0
        public static MetadataWorkspace GetMetadataWorkspace(Func <string, TContext> createFromConnectionString, bool hardCache)
        {
            if (_cachedWorkspace != null)
            {
                return(_cachedWorkspace);
            }

            var cacheName = GetCacheName();

            if (hardCache && File.Exists(cacheName))
            {
                var xDoc = XDocument.Load(cacheName);
                return(_cachedWorkspace = GetMetadataWorkspace(xDoc));
            }

            using (var ctx = createFromConnectionString("App=EntityFramework"))
                using (var ms = new MemoryStream())
                    using (var writer = new XmlTextWriter(ms, Encoding.UTF8))
                    {
                        EdmxWriter.WriteEdmx(ctx, writer);

                        if (hardCache)
                        {
                            ms.Seek(0, SeekOrigin.Begin);
                            using (var file = File.Create(cacheName))
                                ms.WriteTo(file);
                        }

                        ms.Seek(0, SeekOrigin.Begin);
                        var xDoc = XDocument.Load(ms);
                        return(_cachedWorkspace = GetMetadataWorkspace(xDoc));
                    }
        }
        public void CreateInsertOperation_should_return_valid_history_operation()
        {
            var modelBuilder = new DbModelBuilder();
            var model        = modelBuilder.Build(ProviderInfo);
            var edmxString   = new StringBuilder();

            using (var xmlWriter = XmlWriter.Create(
                       edmxString, new XmlWriterSettings
            {
                Indent = true
            }))
            {
                EdmxWriter.WriteEdmx(model, xmlWriter);
            }

            var modelDocument = model.GetModel();

            var historyRepository = new HistoryRepository(ConnectionString, ProviderFactory, "MyKey");

            var historyOperation
                = (HistoryOperation)historyRepository.CreateInsertOperation("Migration1", modelDocument);

            Assert.NotEmpty(historyOperation.Commands);
            Assert.Equal(4, historyOperation.Commands.Single().Parameters.Count());
        }
Exemple #5
0
        public void CreateInsertOperation_should_return_valid_history_operation()
        {
            var modelBuilder = new DbModelBuilder();
            var model        = modelBuilder.Build(ProviderInfo);
            var edmxString   = new StringBuilder();

            using (var xmlWriter = XmlWriter.Create(
                       edmxString, new XmlWriterSettings
            {
                Indent = true
            }))
            {
                EdmxWriter.WriteEdmx(model, xmlWriter);
            }

            var modelDocument = model.GetModel();

            var historyRepository = new HistoryRepository(Mock.Of <InternalContextForMock>(), ConnectionString, ProviderFactory, "MyKey", null, HistoryContext.DefaultFactory);

            var historyOperation
                = (HistoryOperation)historyRepository.CreateInsertOperation("Migration1", new VersionedModel(modelDocument));

            Assert.NotEmpty(historyOperation.CommandTrees);
            Assert.Equal(DbCommandTreeKind.Insert, historyOperation.CommandTrees.Single().CommandTreeKind);
        }
Exemple #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

#if DEBUG
            // Drop, recreate and reseed the database
            Database.SetInitializer(new DbInitializer());
            using (var db = new ListAssistContext())
            {
                db.Database.Initialize(true);
            }

            // Recreate a edmx diagram from the latest model
            using (var ctx = new ListAssistContext())
            {
                using (var writer = new XmlTextWriter(HttpRuntime.AppDomainAppPath.TrimEnd('\\') + @".Data\EntityModelDiagram.edmx", Encoding.Default))
                {
                    EdmxWriter.WriteEdmx(ctx, writer);
                }
            }
#endif
        }
        public static string GetModelXDocument(DbModel model)
        {
            if (model == null)
            {
                return(string.Empty);
            }

            XDocument doc;

            using (var memoryStream = new MemoryStream())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings {
                    Indent = true
                }))
                {
                    EdmxWriter.WriteEdmx(model, xmlWriter);
                }

                memoryStream.Position = 0;

                doc = XDocument.Load(memoryStream);
            }

            return(doc.ToString());
        }
 public static void WriteEdmx(this DbContext context, string outputFilePath)
 {
     EdmxWriter.WriteEdmx(context, XmlWriter.Create(outputFilePath, new XmlWriterSettings()
     {
         Indent = true
     }));
 }
        private static String GetMetadataFromDbContext(Object context)
        {
            var      dbContext = (DbContext)context;
            XElement xele;

            try {
                using (var swriter = new StringWriter()) {
                    using (var xwriter = new XmlTextWriter(swriter)) {
                        EdmxWriter.WriteEdmx(dbContext, xwriter);
                        xele = XElement.Parse(swriter.ToString());
                    }
                }
            } catch (Exception e) {
                if (e is NotSupportedException)
                {
                    // DbContext that fails on WriteEdmx is likely a DataBase first DbContext.
                    return(GetMetadataFromObjectContext(dbContext));
                }
                else
                {
                    throw;
                }
            }

            var ns            = xele.Name.Namespace;
            var conceptualEle = xele.Descendants(ns + "ConceptualModels").First();
            var schemaEle     = conceptualEle.Elements().First(ele => ele.Name.LocalName == "Schema");
            var xDoc          = XDocument.Load(schemaEle.CreateReader());

            var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;

            // This is needed because the raw edmx has a different namespace than the CLR types that it references.
            xDoc = UpdateCSpaceOSpaceMapping(xDoc, objectContext);
            return(XDocToJson(xDoc));
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            if (targetModel != null)
            {
                foreach (EntityModel item in targetModel.Entities)
                {
                    Type dynamicEntityType = DynamicEntityTypeManager.CreateTypeFromEntityDefinition(targetModel, item, DateTime.UtcNow);

                    MethodInfo registerMethod = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(dynamicEntityType);
                    dynamic    configuration  = registerMethod.Invoke(modelBuilder, null);
                    // configuration.MapInheritedProperties();
                    var action = new Action <dynamic>(m =>
                    {
                        m.MapInheritedProperties();
                        m.ToTable(item.Name);
                    });
                    configuration.Map(action);
                    //DataStructures.Attribute primaryKey = item.Attributes.First(a => a.AttributeInfo.IsPrimaryKey == true);
                    //configuration.HasKey(primaryKey

                    /*modelBuilder.Entity<BaseEntity>().Map(m =>
                     * {
                     *  m.MapInheritedProperties();
                     *  m.ToTable(item.Name);
                     * });*/
                    ///.HasKey<string>(ent => ent.Name);
                }
            }

            DbModel model = null;

            if (targetModel.Databases.Count > 0 && !string.IsNullOrEmpty(this.cnnString))
            {
                if (targetModel.Databases[0].Connector.Contains("MSSQL"))
                {
                    var providerFactory = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient");
                    System.Data.Common.DbConnection connection = providerFactory.CreateConnection();
                    connection.ConnectionString = this.cnnString;
                    model = modelBuilder.Build(connection);
                }
            }
            else
            {
                var provider = new DbProviderInfo("System.Data.SqlClient", "2008");
                model = modelBuilder.Build(provider);
            }

            string edmxpath = System.IO.Path.Combine(targetModel.ParentProject.Path, System.IO.Path.ChangeExtension(targetModel.Path, "edmx"));

            if (System.IO.File.Exists(edmxpath))
            {
                System.IO.File.Delete(edmxpath);
            }
            var writer = new XmlTextWriter(edmxpath, Encoding.ASCII);

            EdmxWriter.WriteEdmx(model, writer);
            writer.Flush();
            writer.Close();
            //base.OnModelCreating(modelBuilder);
        }
Exemple #11
0
 public void Model_based_WriteEdmx_throws_when_given_null_writer()
 {
     Assert.Equal(
         "writer",
         Assert.Throws <ArgumentNullException>(
             () => EdmxWriter.WriteEdmx(new DbModel(new DbDatabaseMapping(), new DbModelBuilder()), null)).ParamName);
 }
 public void WriteEdmx_throws_when_using_bad_mapping_that_is_not_caught_by_first_pass_CSDL_validation()
 {
     using (var context = new InvalidMappingContext())
     {
         Assert.Throws <ModelValidationException>(
             () => EdmxWriter.WriteEdmx(context, XmlWriter.Create(Stream.Null)));
     }
 }
        public static string GetEdmx(this DbContext context)
        {
            StringBuilder sb        = new StringBuilder();
            XmlWriter     xmlWriter = XmlWriter.Create(sb);

            EdmxWriter.WriteEdmx(context, xmlWriter);
            return(sb.ToString());
        }
Exemple #14
0
        public void Generate()
        {
            var sw = Stopwatch.StartNew();

            byte[] sourceHash    = GetOrmHash();
            string sampleEdmFile = Path.Combine(Paths.GeneratedFolder, EntityFrameworkMetadata.SegmentsFromCode.First().FileName);
            var    edmExtensions = EntityFrameworkMetadata.SegmentsFromCode.Select(s => Path.GetExtension(s.FileName));

            if (_cache.RestoreCachedFiles(sampleEdmFile, sourceHash, Paths.GeneratedFolder, edmExtensions) != null)
            {
                _performanceLogger.Write(sw, "EntityFrameworkMetadata: Restore cached EDM files.");
            }
            else
            {
                var connection = new SqlConnection(_connectionString);

                var dbConfiguration = (DbConfiguration)_dom.GetType("Common.EntityFrameworkConfiguration")
                                      .GetConstructor(new Type[] { })
                                      .Invoke(new object[] { });

                var dbContext = (DbContext)_dom.GetType("Common.EntityFrameworkContext")
                                .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(DbConnection), dbConfiguration.GetType(), typeof(IConfiguration) }, null)
                                .Invoke(new object[] { connection, dbConfiguration, _configuration });

                string edmx;
                using (var stringWriter = new StringWriter())
                    using (var xmlWriter = new XmlTextWriter(stringWriter))
                    {
                        xmlWriter.Formatting = System.Xml.Formatting.Indented;
                        EdmxWriter.WriteEdmx(dbContext, xmlWriter);
                        edmx = stringWriter.ToString();
                    }

                _performanceLogger.Write(sw, "EntityFrameworkMetadata: Extract EDMX.");

                foreach (var segment in EntityFrameworkMetadata.SegmentsFromCode)
                {
                    string startTag = "\r\n    <" + segment.TagName + ">\r\n";
                    string endTag   = "\r\n    </" + segment.TagName + ">\r\n";

                    int start            = edmx.IndexOf(startTag, StringComparison.Ordinal);
                    int end              = edmx.IndexOf(endTag, StringComparison.Ordinal);
                    int alternativeStart = edmx.IndexOf(startTag, start + 1, StringComparison.Ordinal);
                    int alternativeEnd   = edmx.IndexOf(endTag, end + 1, StringComparison.Ordinal);
                    if (start == -1 || alternativeStart != -1 || end == -1 || alternativeEnd != -1)
                    {
                        throw new Exception("Unexpected EDMX format. " + segment.TagName + " tag locations: start=" + start + " alternativeStart=" + alternativeStart + " end=" + end + " alternativeEnd=" + alternativeEnd + ".");
                    }

                    string segmentXml = edmx.Substring(start + startTag.Length, end - start - startTag.Length);
                    File.WriteAllText(Path.Combine(Paths.GeneratedFolder, segment.FileName), segmentXml, Encoding.UTF8);
                }

                _performanceLogger.Write(sw, "EntityFrameworkMetadata: Save EDM files.");
            }

            _cache.SaveHash(sampleEdmFile, sourceHash);
        }
        public void EDMX_can_be_written_from_DbModel()
        {
            var edm         = SimpleModelContext.CreateBuilder().Build(ProviderRegistry.Sql2008_ProviderInfo);
            var edmxBuilder = new StringBuilder();

            EdmxWriter.WriteEdmx(edm, XmlWriter.Create(edmxBuilder));

            SanityCheckEdmx(edmxBuilder);
        }
Exemple #16
0
        private static XDocument GetModel(this DbContext context)
        {
            var document = GetModel(delegate(XmlWriter w)
            {
                EdmxWriter.WriteEdmx(context, w);
            });

            return(document);
        }
Exemple #17
0
        public void GenerateEdmxForCodeFirstDBContext()
        {
            var path = HttpContext.Current.Server.MapPath("~/Models/store.edmx");

            using (var writer = new XmlTextWriter(path, Encoding.Default))
            {
                EdmxWriter.WriteEdmx(db as StoreAppContext, writer);
            }
        }
 static void Main(string[] args)
 {
     using (var ctx = new MyContext())
     {
         EdmxWriter.WriteEdmx(ctx, XmlWriter.Create(Console.Out, new XmlWriterSettings {
             Indent = true
         }));
     }
 }
Exemple #19
0
 public static void GerarDiagrama()
 {
     using (var ctx = new ContextoEF())
     {
         using (var writer = new XmlTextWriter(@"C:\Users\edera\Source\Repos\lojavirtual\WebAppLab2Turma20161\DiagramaDeClasse\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
Exemple #20
0
        public static void WriteEdmx(string filePath)
        {
            var context  = new MyDbContext();
            var settings = new XmlWriterSettings();

            settings.Indent = true;
            var writer = XmlWriter.Create(filePath, settings);

            EdmxWriter.WriteEdmx(context, writer);
        }
Exemple #21
0
 public static void GerarDiagrama()
 {
     using (var ctx = new ContextoEF())
     {
         using (var writer = new XmlTextWriter(@"C:\Users\racro\Source\Repos\SIGESF_V4\SIGESF\DiagramaDeClasse\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
 static void Main(string[] args)
 {
     using (var ctx = new KatSystemDbContext())
     {
         using (var writer = new XmlTextWriter(@"c:\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
Exemple #23
0
 public static void GerarDiagrama()
 {
     using (var ctx = new ContextoEF())
     {
         using (var writer = new XmlTextWriter(@"C:\Users\Alexsandro Moreira\Documents\Visual Studio 2015\Projects\SiCED\SiCED\DiagramaDeClasse\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
 private void GenerateERDiagram()
 {
     using (var context = new ApplicationDbContext())
     {
         using (var writer = new XmlTextWriter(@"C:\My Files\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(context, writer);
         }
     }
 }
 public static void GerarDiagrama()
 {
     using (var ctx = new ContextoEF())
     {
         using (var writer = new XmlTextWriter(@"C:\Users\wande\Source\Repos\WandelFeics\Clinica\DiagramadeClasses\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
        /// <summary>
        /// Writes csdl, msdl, and ssdl files into the current directory for the model generated from
        /// the given model builder.
        /// </summary>
        /// <param name="builder"> The builder. </param>
        /// <param name="filename"> The base filename to use for csdl, msdl, and sssl files. </param>
        public static void WriteMetadataFiles(DbModelBuilder builder, string filename)
        {
            var xml = new StringBuilder();

            EdmxWriter.WriteEdmx(
                builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008")),
                XmlWriter.Create(xml));

            WriteMetadataFiles(xml.ToString(), filename);
        }
Exemple #27
0
 public static void GerarDiagrama()
 {
     using (var ctx = new Contexto())
     {
         using (var writer = new XmlTextWriter(@"C:\Users\luqta\OneDrive\Documentos\visual studio 2015\Projects\WebAppOS\WebAppOS\DiagramaDeClasse\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
 public static void GerarDiagrama()
 {
     using (var ctx = new ContextoEF())
     {
         using (var writer = new XmlTextWriter(@"D:\becap\programas c#\PI\Projeto de Conclusao Refeito\WebAppAdvocacia\DiagramaDeClasse\Model.edmx", Encoding.Default))
         {
             EdmxWriter.WriteEdmx(ctx, writer);
         }
     }
 }
Exemple #29
0
        public static void ExportModelToFile(this DbContext ctx, String filename)
        {
            XmlWriterSettings settings = new XmlWriterSettings {
                Indent = true
            };

            using (XmlWriter writer = XmlWriter.Create(filename, settings))
            {
                EdmxWriter.WriteEdmx(ctx, writer);
            }
        }
 public void Context_based_WriteEdmx_throws_when_used_with_Model_First_DbContext()
 {
     using (
         var context = new DbContext(
             new EntityConnection(SimpleModelEntityConnectionString),
             contextOwnsConnection: true))
     {
         Assert.Throws <NotSupportedException>(() => EdmxWriter.WriteEdmx(context, XmlWriter.Create(Stream.Null)))
         .ValidateMessage("EdmxWriter_EdmxFromModelFirstNotSupported");
     }
 }