6

目前,我正在开发一个通过 LINQ-to-SQL 依赖(并因此连接到)各种数据库的应用程序。对于其中一个数据库,连接字符串可能会有所不同,因此是可配置的 - 但是,该数据库的架构对于所有连接字符串都是相同的。

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

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

那么。目前,验证检查执行如下:

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

虽然这确实有效,但确定 valid 的值需要相当长的时间(每个 Table 的每条记录都被触及),最终导致超时。那么,有没有一种更快、更可靠的方法来判断某个Table<T>的 a是否DataContext真的作为表存在于对应的数据库中呢?

4

2 回答 2

5

这是一个(未经测试的)想法:

抓住你的桌子的名字。您可以硬编码,也可以通过编程方式获取它

TableAttribute attribute = (TableAttribute)typeof(MyTableObject)
                           .GetCustomAttributes(typeof(TableAttribute), true)
                           .Single();
string name = attribute.Name;

MyTableObject是包含在您的 LINQ-to-SQL 生成的对象,Table即.TTable<T>

TableAttributeSystem.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);    
于 2009-07-02T13:29:30.313 回答
4

杰森的回答略有变化(我给了他一个赞成票:))

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();
}
于 2010-07-02T16:15:05.220 回答