Click here to Skip to main content
15,887,376 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Problem

I work on asp.net core 2.1 project and i need to design function pass to it table name

get columns exist on that table ?

suppose i have table employee have two column employeeid,employeename

then when pass table name employee to function will return two columns

employeeid,employeename .

C#
public List<string> GetColumns<T>(How to pass table name here as string)
        {
            var columnNames = _context.Model.FindEntityType(typeof(T))
                   .GetProperties().Select(x => x.Relational().ColumnName).ToList();
            return columnNames;
        }

How to pass table name as string in function above
i try but it give me compile error
on T

What I have tried:

public List<string> GetColumns<T>(List<T> _)
       {
           var columnNames = _context.Model.FindEntityType(typeof(T))
                  .GetProperties().Select(x => x.Relational().ColumnName).ToList();
           return columnNames;
       }
Posted
Updated 11-Mar-19 6:36am
Comments
[no name] 11-Mar-19 12:18pm    
(List<t> _)

What's that supposed to mean? This is a "string": string name
ahmed_sa 11-Mar-19 12:19pm    
public List<string> GetColumnNames(string tablename)
{
ahmed_sa 11-Mar-19 12:21pm    
public List<string> GetColumnNames(string tablename)
{
var columnNames = _context.Model.FindEntityType(typeof(T))
.GetProperties().Select(x => x.Relational().ColumnName).ToList();
return columnNames;
}
ahmed_sa 11-Mar-19 12:21pm    
I GET ERROR ON T

1 solution

Why don't you work off of Saturday's question
How to get fields exist on table by passing table name by using ASP.NET core 2.1 ?[^]

To build onto that
1. Create a new Model which mirrors the basics of the sql system table which has the column information, Information_Schema.Columns. While Entity Framework may not like working with that table, you can always use ADO.
SQL
SELECT  TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE
     ,  CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   (TABLE_SCHEMA <> 'sys')

2. When you want to run your function, you can populate a collection of that new Model, and use LINQ or whatever you want to perform the search.

This approach would also allow you to find all tables that have a particular named column.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900