gpt4 book ai didi

c# - 如何在不使用模型的情况下使用 Entity Framework 执行原始 SQL 查询?

转载 作者:IT王子 更新时间:2023-10-29 04:01:22 25 4
gpt4 key购买 nike

我正在尝试学习 C# ASP.NET MVC 5。我正在尝试使用 Entity Framework 来完成我所做的一切。

但是,我需要运行原始 SQL 查询并将结果返回到数组中。

这是我到目前为止所做的。

我创建了我的上下文类,它允许我连接到服务器,它还允许我在运行时更改数据库。

这是我的上下文类

using ScripterEngine.Models;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace ScripterEngine.DataAccessLayer
{
public class BaseContext : DbContext
{
protected string connectionName;
public DbSet<Campaign> Campaign { get; set; }

/**
* Created the connection to the server using the giving connection string name
*
* @param connName
*/
public BaseContext(string connName = "BaseConnection")
: base(connName)
{
connectionName = connName;
}

/**
* Changes the default database
*
* @param databaseName
*/
public BaseContext setDatabase(string databaseName)
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);

//change the database before creating the new connection
builder.InitialCatalog = databaseName;

string sqlConnectionString = builder.ConnectionString;

return new BaseContext(sqlConnectionString);
}
}
}

而这里如何建立联系就是我所做的

BaseContext db1 = new BaseContext("server1");
var db1New = db1.setDatabase("someTableName");
string tableName = "SomeTableName";

var results = db1New.Database.SqlQuery("SELECT LOWER(column_name) AS column_name FROM information_schema.columns WHERE table_name = @tableName", tableName).ToArray();

这会引发错误

The type arguments for method 'System.Data.Entity.Database.SqlQuery(string, params object[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. C:.NET Projects\ScripterEngine\ScripterEngine\Controllers\CampaignController.cs 42 27 ScripterEngine

我怎样才能执行这个原始查询?

最佳答案

指定string作为类型参数。

var results = db1New.Database.SqlQuery<string>("SELECT LOWER(column_name) AS column_name FROM information_schema.columns WHERE table_name = @p0", tableName).ToArray();
^^^^^^

关于c# - 如何在不使用模型的情况下使用 Entity Framework 执行原始 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com