[英]How do I connect to database in ASP.NET Core Web API without using EF?
I am attempting to create an ASP.NET Core Web API without using EF Core. 我试图在不使用EF Core的情况下创建ASP.NET Core Web API。 Instead, I would like to use System.Data.SQLClient to connect to SQL server, and query it using plain old SQL. 相反,我想使用System.Data.SQLClient连接到SQL服务器,并使用普通的旧SQL进行查询。 That said, I'm having a bit of trouble figuring out how to establish the connection. 也就是说,我在确定如何建立连接方面遇到了一些麻烦。 I've found a lot of tutorials online that address how to do this with EF. 我在网上找到了很多关于如何用EF来解决这个问题的教程。 But, I'm a bit perplexed as to how it's done without it. 但是,如果没有它,我有点感到困惑。
You do it exactly the same way as you would in any .net application: 您可以使用与任何.net应用程序完全相同的方式执行此操作:
using (var conn = new System.Data.SqlClient.SqlConnection(connectionString)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "SELECT 'hello world'";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
You will find that some parts of asp.net core require EF, like the identity claims stuff, so you will need to handle your own authentication and won't be able to use their security attributes and the like. 您会发现asp.net核心的某些部分需要EF,例如身份声明内容,因此您需要处理自己的身份验证,并且无法使用其安全属性等。 I've gone this route on several asp.net core projects with no regrets 我已经在几个asp.net核心项目上走了这条路,没有遗憾
You must use SqlConnection and SqlCommand classes. 您必须使用SqlConnection和SqlCommand类。 From the documentation 从文档中
private static void CreateCommand(string queryString, string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
CreateCommand("insert into...", "[your connection string]");
Aditionally, Dapper is a good option for accessing data, is an object mapper that extends IDbConnection, so you don't have to worry about object creation. 另外, Dapper是访问数据的好选择,是扩展IDbConnection的对象映射器,因此您不必担心对象创建。 From dapper's docummentation 来自小巧玲珑的文件
public class Dog
{
public int? Age { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
public float? Weight { get; set; }
public int IgnoredProperty { get { return 1; } }
}
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.