以编程方式检索流利的配置,而无需实例化DbContext [英] Retrieving fluent configuration programmatically without instantiating DbContext

查看:68
本文介绍了以编程方式检索流利的配置,而无需实例化DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DbContext派生类,其成员实体类是使用Fluent API配置的。我想以编程方式检索这些配置和关系。

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 code to do this is already in place and I am porting it to a T4 template for code generation.

虽然大多数代码生成使用反射,但流畅的配置需要使用以下代码:要实例化的上下文类,以便获得:

While most of the code generation uses reflection, fluent configuration requires the context class to be instantiated in order to get:


  • ObjectContext

  • EntityObjects

  • EntityContainer

  • EntitySets

  • Etcetera

  • ObjectContext
  • EntityObjects
  • EntityContainer
  • EntitySets
  • Etcetera

因为我们没有使用属性属性,所以反射没有帮助。

Since we are not using property attributes, reflection is of no help.

这在运行时效果很好,但是在T4模板中实例化DbContext会导致所有错误。各种各样的问题。有时它会导致VS崩溃,产生奇怪的错误,创建周期性依赖关系等。

This works fine during runtime, but instantiating the DbContext within a T4 template is causing all sorts of problems. It sometimes crashes VS, gives weird errors, creates a cyclic dependency, etc.

如果我调试T4模板,它的确运行没有错误,但是后台进程锁定了项目包含DbContext类和实体。因此,每次对实体进行更改时,我必须重新启动VS三次,执行不同的步骤。

If I debug the T4 template, it does run without errors but the background process locks the project containing the DbContext class and entities. So every time there is a change to the entities, I have to restart VS three times performing different steps. Yuck!

我想知道是否存在一种无需实例化上下文类即可检索实体元数据/配置的方法。

I was wondering if there is a way to retrieve entity metadata/configuration without instantiating the context class. Any guidance would be appreciated.

推荐答案

好,您需要加载上下文,因为它需要调用 OnModelBuilding(DbModelBuilder)至少要做一次生意;

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.

如果需要,可以使用 EdmxWriter ;

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();
    }

这将为您提供带有数据模型的XML文档。您可能可以通过一个进程将其保存到磁盘,然后在TT文件中查询该文件。

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.

这篇关于以编程方式检索流利的配置,而无需实例化DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆