[英]C# Entity Framework Core write raw SQL without model
First of all, I have seen this post: Raw SQL Query without DbSet - Entity Framework Core but I feel like it does not answer my question.首先,我看过这篇文章: Raw SQL Query without DbSet - Entity Framework Core但我觉得它没有回答我的问题。
I have an ASP.NET Core MVC project with Entity Framework Core (newest at this date).我有一个带有实体框架核心的 ASP.NET 核心 MVC 项目(目前最新)。
What I need to do is:我需要做的是:
public IActionResult MyView(string NameOfTable)
{
// send model that is same as NameOfTable
// or
// send something like List<string> that has properties and names of columns
return View();
}
What I want to do is call a function and send the name of a table in database.我想要做的是调用 function 并发送数据库中表的名称。 It will find the table in the database and return the properties of table (column names, types of columns[int/ varchar..]).
它将在数据库中找到表并返回表的属性(列名、列类型[int/varchar..])。
What I think will work: either write raw SQL to database.我认为可行的方法:将原始 SQL 写入数据库。
What I think is good answer: some snippet of how to write raw SQL to query the database without knowing a model.我认为是好的答案:一些如何编写原始 SQL 以在不知道 model 的情况下查询数据库的片段。 Or some way of overcoming this problem.
或者某种克服这个问题的方法。
Thanks for everything.感谢一切。 Sorry if this is dumb question.
对不起,如果这是一个愚蠢的问题。
Sorry for bothering you all.很抱歉打扰大家。 I have found solution.
我找到了解决方案。 Here it is:
这里是:
public class AA
{
public string One { get; set; }
public string Two { get; set; }
}
private async Task pokus()
{
List<AA> groups = new List<AA>();
var conn = _db.Database.GetDbConnection();
try
{
await conn.OpenAsync();
using (var command = conn.CreateCommand())
{
string query = "SELECT * "
+ "FROM TABLE";
command.CommandText = query;
DbDataReader reader = await command.ExecuteReaderAsync();
if (reader.HasRows)
{
while (await reader.ReadAsync())
{
try
{
var row = new AA { One = reader.GetString(1), Two = reader.GetString(2) };
groups.Add(row);
}
catch { }
}
}
else
{
Console.WriteLine("Dont have rows");
}
reader.Dispose();
}
}
finally
{
conn.Close();
}
foreach(AA s in groups)
{
Console.WriteLine(s.One);
Console.WriteLine(s.Two);
}
}
I hope it will help somebody.我希望它会帮助某人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.