简体   繁体   中英

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.

I have an ASP.NET Core MVC project with Entity Framework Core (newest at this date).

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. It will find the table in the database and return the properties of table (column names, types of columns[int/ varchar..]).

What I think will work: either write raw SQL to database.

What I think is good answer: some snippet of how to write raw SQL to query the database without knowing a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM