Retrieving fluent configuration programmatically without instantiating DbContext

前端 未结 1 1536
逝去的感伤
逝去的感伤 2021-01-22 10:31

I have a DbContext derived class whose member entity classes are configured using Fluent API. I want to retrieve these configurations and relationships programmatically. the cod

1条回答
  •  心在旅途
    2021-01-22 10:47

    Well, you need to load the context because it needs to call OnModelBuilding(DbModelBuilder) at least once to do it's business; otherwise there is no model to interrogate.

    If you want, you can store off the information as XML using EdmxWriter;

        public static string ToEdmx(this System.Data.Entity.DbContext context)
        {
            var sb = new StringBuilder();
    
            using (var textWriter = new StringWriter(sb))
            using (var xmlWriter = System.Xml.XmlWriter.Create(textWriter, new System.Xml.XmlWriterSettings { Indent = true, IndentChars = "    " }))
            {
                System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(context, xmlWriter);
                textWriter.Flush();
            }
    
            return sb.ToString();
        }
    

    This will give you an XML document with the data model. You can probably save that to disk in one process, and interrogate that file in your TT file.

    0 讨论(0)
提交回复
热议问题