如何遍历DataContext中的表和Test-Read Records

本文关键字:Test-Read Records DataContext 何遍历 遍历 | 更新日期: 2023-09-27 17:49:36

我正在尝试创建一个TestMethod,它将枚举我的数据上下文中的表,并尝试从每个表中读取一条记录。测试的目标是确保我的.dbml文件与底层数据库同步。到目前为止我有什么:

[TestMethod]
public void TestDataContextTables()
{
    using ( MyDataContext dataContext = new MyDataContext() )
    {
        int count = 0;
        IEnumerable<MetaTable> tableList = dataContext.Mapping.GetTables();
        foreach ( MetaTable table in tableList )
        {
            Debug.Print( "Testing " + table.TableName + "..." );
            // method to restore >= 1 record using LINQ...
            //Object dummy = from t in dataContext.Mapping.GetTables().Skip( count ).Take( 1 ) select t;  <-- wrong (1)
            //Object dummy = from t in dataContext.Mapping.GetTable( table.RowType.GetType() ) select t; <-- also wrong (2)
            //Object dummy = from t in dataContext.Mapping.GetTable( table.RowType.GetType() ).GetType() select t; <-- also wrong (3)
            Debug.Print( "OK'n" );
            count++;
        }
    }
}

LINQ语句(1)似乎没有读取任何实际数据。LINQ语句(2)给出了编译时错误"无法找到源类型'MetaTable'的查询模式的实现",(3)给出了错误"无法找到源类型'System.Type'的查询模式的实现"。后两者告诉我,我指的是一个元东西,而我应该指的是一个东西

我正在寻找的是一种在LINQ语句中引用DataContext中的每个表并从每个记录返回一行的方法,以确保LINQ生成的SELECT与底层数据库一致。

如何遍历DataContext中的表和Test-Read Records

您可以使用select name from sys.tables通过LINQ枚举表名并使用SqlQuery(假设您正在使用EF):

var result = db.Database.SqlQuery("select * from " + yourTableName).ToList();