【问题标题】:LINQ to SQL: using string filename to create a DataContext at runtimeLINQ to SQL:使用字符串文件名在运行时创建 DataContext
【发布时间】:2010-11-14 03:49:32
【问题描述】:

使用 FileInfo 我可以找到 DataContext .dbml 文件的文件名。

只要我声明:

Dim DataModel = New AttributeMappingSource().GetModel(GetType(NorthwindDataContext))

使用 System.Data.LINQ.Mapping 我可以找到所有表的名称以及它们的列和关系。

这一切都要感谢 Jomo Fisher 的精彩帖子:LINQ to SQL Trick: Get all Table [and Column] Names: http://blogs.msdn.com/jomo_fisher/archive/2007/07/30/linq-to-sql-trick-get-all-table-names.aspx

但是我如何在不明确知道 DataContext 对象的情况下获得相同的结果呢? 我的意思是我该如何“替换”这个:

            GetType(NorthwindDataContext))

与:

            dim myDCFile as String = "Northwind.dbml"
            Dim DataModel = .../... GetType(myDCFile))

【问题讨论】:

    标签: linq-to-sql datacontext


    【解决方案1】:

    你可以试试这样的:

    Assembly dataAssembly = Assembly.Load("Your.Data.Assembly");
    
    Type dataContextType = dataAssembly.GetTypes()
               .FirstOrDefault(x => x.IsSubclassOf(typeof(DataContext)));
    

    您基本上会加载数据程序集并搜索第一个数据类型,它是DataContext 的子类型。

    然后你可以将它传递给你的方法:

    Dim DataModel = New AttributeMappingSource().GetModel(dataContextType)
    

    马克

    【讨论】:

    • 谢谢 Marc... 但是... 你测试过代码 sn-p 吗?由于我更喜欢​​ VB,所以我翻译了您的代码: Dim dataAssembly As Assembly = Assembly.Load("Your.Data.Assembly") Dim dataContextType As Type = dataAssembly.GetTypes().FirstOrDefault(Function(x) x.IsSubclassOf(Type.GetType(DataContext))) 如您所见, (typeof(DataContext)" 已转换为 "(Type.GetType(DataContext)" 如果我​​知道为什么该死!!!但现在的问题是 VB声明 (DataContext) 部分,说“DataContext 是一种类型,不能用作表达式”。仍然震惊......可悲的是!
    • 我将它作为 C# 代码进行了测试,是的。我的 VB 不够流利,无法知道这里的翻译是怎么回事,抱歉。
    猜你喜欢
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多