目前,我正在开发依赖于(并因此连接到)通过LINQ到SQL的各种数据库的应用程序。对于数据库中的一个,连接字符串可能会发生变化,因此是可配置的 - 然而,该数据库的模式对于所有连接字符串相同。

由于可配置的连接字符串的,我想我的应用程序的启动过程中验证的DataContext,以确保所有表和视图我的应用程序使用,是可用的。

Table<T>对象的DataContext对象总是初始化 - 即使相应的SQL表或视图不具有任何记录。

所以然后。目前,如下验证检查被执行:

        bool valid = _dataContext.Articles.Count() > 0
            && _dataContext.Customers.Count() > 0
            && _dataContext.Orders.Count() > 0;

虽然这确实工作,有效的值的确定需要相当长的时间(每个表的每个记录被触摸),这最终导致超时。那么,有没有一个更快,更可靠的方法来确定某一Table<T>DataContext是否真的存在如在相应的数据库中的表?

有帮助吗?

解决方案

下面是一个(未测试)的想法:

抓住你的表的名称。你可以把它在硬编码,也可以通过

编程抓住它
TableAttribute attribute = (TableAttribute)typeof(MyTableObject)
                           .GetCustomAttributes(typeof(TableAttribute), true)
                           .Single();
string name = attribute.Name;

MyTableObject是包含在你的Table,即在T通用参数Table<T>的LINQ到SQL生成的对象。

TableAttribute 是在 System.Data.Linq.Mapping 。)

使用 DataContext.ExecuteQuery 方法如在

var db = new MyDataContext();
var results = db.ExecuteQuery<string>("SELECT name FROM dbo.sysobjects WHERE xtype = 'U'");
bool hasTable = results.Any(s => "dbo." + s == name);    

其他提示

在杰森的回答略有变化(我给了他一个给予好评:))

public bool TableExistsInDatabase<T>()
{
  TableAttribute attribute = (TableAttribute)typeof(T)
                             .GetCustomAttributes(typeof(TableAttribute), true)
                             .Single();

  var result = ExecuteQuery<bool>(
                String.Format(
                  "IF OBJECT_ID('{0}', 'U') IS NOT NULL
                   SELECT CAST(1 AS BIT) ELSE 
                   SELECT CAST(0 AS BIT)", attribute.Name));

  return result.First();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top