在 Visual Studio 2017 年,我如何使用 "C# Interactive" window 查询我的 "Data Connections" 中的来源

How can I use, in Visual Studio 2017, the "C# Interactive" window to query a source in my "Data Connections"

我在 "Data Connections"(在 "Server Explorer" 视图中)连接到外部 SQL 服务器。我可以右键单击我的 SQL 源并单击 "New Query" 以使用 SQL 语句快速查找数据。

我想改用 LINQ,而且我认为 "C# Interactive" window 是一种快速有效的方法。我的问题是我不知道如何访问我的 'open' 数据连接。无法识别数据库或表的名称。

这个灵魂作品!

    SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NoOfConnections,
    loginame as LoginName
    FROM
    sys.sysprocesses
    WHERE 
    dbid > 0
    GROUP BY 
dbid, loginame

你可以看看这个linkfind number of open connection on database

我提出的解决方案可能不是您正在寻找的,但我认为它会帮助您弄清楚您需要什么。我做过类似的事情的一种方法是创建一个 DA 库并在 C# Interactive Window 中使用它。下面是示例:

我会有一个 class 图书馆项目,MyProject.MyDA:

namespace MyDa
{
    public class CustomerDa
    {
        public DataTable LoadData(string sqlCommandText = "")
        {
            //do your try catch finally and all the good stuff
            var connString = @"Data Source=ServerName;Initial Catalog=AdventureWorks2014;Integrated Security=SSPI;";
            var conn = new SqlConnection(connString);
            SqlDataReader dataReader;
            //you could accept the command text as a parameter
            string sql = "select top 10 * FROM [AdventureWorks2014].[HumanResources].[Department]";
            var result = new DataTable("Department");
            conn.Open();
            SqlCommand command = new SqlCommand(sql, conn);
            dataReader = command.ExecuteReader();
            result.Load(dataReader);
            dataReader.Close();
            command.Dispose();
            conn.Close();
            //instead of a datatable, return your object
            return result;
        }
    }
}

构建你的 DA 项目,现在在 C# Interactive,你会做这样的事情:

> #r "D:\blah\Blah\MyDa\bin\Debug\MyDa.dll"
> using MyDa;
> var a = new CustomerDa();
> var r = a.LoadData();
> r.Rows[0]
DataRow { HasErrors=false, ItemArray=object[4] { 1, "Engineering", "Research and Development", [4/30/2008 12:00:00 AM] }, RowError="", RowState=Unchanged, Table=[] }
> r.Rows.Count //you can do all the good LINQ stuff now on the result
10

你可以这样做,但我觉得这个流程比我想要的需要更多的工作和仪式,而且仍然不完美。无论如何,这是完成您正在寻找的东西的一种方法。如果您更喜欢使用 LINQ.

进行查询,我还建议您使用 LinqPad

我通过创建一个 class 库打开与 EF 数据模型的连接,将 DLL 导入 C# 交互式 window,并对数据模型执行 Linq 语句来实现它.

首先,创建 class 库,添加 EF 数据模型,并修改 DbContext(实体)class 以使用采用连接字符串的构造函数。您需要这样做才能从 c# 交互式 window 中使用此库,因为如果不这样做,交互式 window 将查找带有连接字符串的 app.config 文件。

public partial class YourDBEntities : DbContext
{
    public YourDBEntities(string connectionString)
        : base(connectionString)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    ....
}

如果您的 class 库,请添加一个 class 和用于获取数据上下文的静态方法:

public class AccessorClass
{
    public static YourDBEntities GetDataContext()
    {
        return new YourDBEntities("metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=\";data source=xxxxxxx;initial catalog=xxxxxxx;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework\";");
    }
}

编译 class 库,然后将 DLL 导入您的交互式 window,然后查询:

> #r "C:\Path...\bin\Debug\YourClassLibrary.dll"
> using YourClassLibrary;
> using (var ctx = AccessorClass.GetDataContext())
. {
.     Console.Write(ctx.Orders.Where(c => c.ProjectID == 309).Count().ToString());
. }

是的,您可以在 Solution Explorer 中右键单击主项目,然后单击 Initialize Interacive with Project。这将为您构建项目并将所有 dll 导入交互式 window。然后就可以开始抓了!

例如,使用 Entity Framework 时,您需要站起来 DbContext。输入类似...

> var context = new My.Namespace.MyDataContext("blah blah blah");

我写的 "blah blah blah" 你需要添加你的连接字符串。交互式控制台不知道您的 .config 文件,因此您需要提供连接字符串。

Note: To be able to do this make sure you have the nameOrConnectionString constructor override on your data context.

现在您已经有了上下文,它就像通常查询上下文一样简单...

> context.Users.Where(u => u.IsActive).Select(u => u).ToList()

Important
Take note that I have left the semicolon (;) off the end of the query. This is important as it tells the console to output the value of the query/command/line of code. Nothing will happen if you leave this off.