I am using EntityFramework v6.1 with MySql.Data.Entity.EF6 v 6.8.3.0.
I am attempting to get the "Headers" or "Column Names" for data inside tables. I have a table called "dbases" and I need to get the Column Names from within ADO.NET, please help!
using (var connection = new hyperion_collectionsmaxEntities())
{
var portfolios = connection.portfolios.ToList();
portfolios.ForEach(o => comboBox1.Items.Add(o.portfolio1));
var statuses = connection.adminstatus.ToList();
statuses.ForEach(o => chkLstBoxStatuses.Items.Add(o.statusname));
//var headers = connection.dbases ?? <~~~
}
One way to get at the column names is to query to MetaTables:
SELECT COLUMN_NAME, TABLE_NAME
FROM information_schema.COLUMNS
WHERE information_schema.COLUMNS.table_schema = 'dbases';
There are a lot of interesting data there. For simply getting at the Column Name and the (default) Header you can use the DataTable.Column's properties:
yourTable.Columns[columnIndex].ColumnName
yourTable.Columns[columnIndex].Caption
If EF has special ways I don't know about them.. but in the end imo the data should go into the DataTable..
Related
I have a program in c# (asp.net environment) that dynamically runs ORACLE queries.
the queries can be like:
select * from app_costumers;
select a.first_name, a.last name, b.salary from app_costumers inner join app_costs b on a.id = b.id;
(As you can see, this is sometimes about a single table and sometimes more.
Sometimes writing the column names and sometimes using only in "*").
until now, I returned only the results,
But now I need to return the names of the results columns.
Do you have any idea how to do this?
(I can't use something like this:
SELECT column_name FROM user_tab_cols WHERE table_name = UPPER ('app_costumers');
Because it only fits for one table ...).
Thank you
You can use reader.GetName(i), for example:
var reader = cmd.ExecuteReader();
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
{
columns.Add(reader.GetName(i));
}
I'm working with TSQL and C#. I have two queries that return strings:
string[] allSubcategories = dt.AsEnumerable().Select(x => x.Field<string>("SubcategoryName")).Distinct().ToArray();
var redMark = db.GetTableBySQL("SELECT * FROM RedMarkItems");
string[] redMarkColumns = redMark.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
So, as you can see I have two different arrays, first I get subcategoriesNames:
and all columns of table RedMarkItems:
That I want to do is to create column dynamically, I mean, if subcategorieName does not exist as column in RedMarkItems do an Update and create it someting like:
var createColumn = db.ExeSQL($"ALTER TABLE RedMarkItems ADD {ColumnName} BIT");
How can I compare if subcategorieName does not exist as column in RedMarkItems table? Then create column as my query? Regards
If you want to know if a particular column exists in an already filled DataTable using the Linq approach then it is just:
bool exists = redMark.Columns.Cast<DataColumn>().Any(x => x.ColumnName == "SubCategoryName");
Instead, if you want to ask this info directly to the database then use the INFORMATION_SCHEMA views The Columns view is the one to use with a query like this.
string query = #"IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.Column
WHERE Column_Name = #colName)
SELECT 1 ELSE SELECT 0";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.Add("#colName", SqlDbType.NVarChar).Value = "SubCategoryName";
bool exists = (cmd.ExecuteScalar() == 1);
Now, the part about creating the column is pretty simple as code per se. It is just an appropriate ALTER TABLE. But there are a lot of things to be cleared before. What will be the datatype of the new column? What will be its length and precision? What will be the constraints applied to it (Null/Not Null defaults etc)? As you can see all these info are very important and require to be defined somewhere in your code.
I am using DotnetBar,
Have used Supergrid and populated its grid panel by data from particular table,
Now I have dynamically added a Column as shown below,
GridPanel panel = superGridControl.PrimaryGrid;
string query = #"select ........";
DataSet ds_classes = RunQuery(query); // RunQuery is method to
// connect to the database and
// execute the query to return Dataset
if (ds_classes.Tables.Count > 0)
{
panel.DataSource = ds_classes.Tables[0].DefaultView;
}
GridColumn gc = new GridColumn();
gc.HeaderText = "Attribute Type";
panel.Columns.Add(gc);
which is shown in below image
here ID and ATRIBUTES column get populated by different dataset, and I just want Attribute Type column should get populated by different dataset,
Any help will be greatly appreciated.
Use inner join in your query to join the two tables and then display that. You can omit the code that adds the column.
I have two tables I am using to fill a gridview. The tables have a common field named RangeActivityID. My problem is that the database is very old and some of the older entries do not match up IDs between tables, so I am unable to add an association between them in the database.
I do not care about the old data which doesn't match up, so in my .dbml file, I manually created an association in order to select good data from both tables. This is the LINQ query I have:
var collective = from p in rangeConnection.RangeActivities
orderby p.RangeActivityID
select new
{
TestName = p.TestName,
DateTime = p.ActivityDateTime,
Notes = p.Notes,
//RoundSerialNumber = p.RoundFire.RoundSerialNumber,
//RoundType = p.RoundFire.RoundType,
//LotStockNumber = p.RoundFire.LotNumber
};
I can set my grid datasource to 'collective' and everything works, but if I uncomment the three commented lines, the query returns no results because the tables have data that doesn't meet the association criteria. Is there a way to have the LINQ query ignore results that do not match up?
Thanks in advance!
Try to add where p.RoundFire != null criteria.
Suggest a join instead, and emulating a SQL LEFT JOIN.
var q = from p in rangeConnection.RangeActivities
join r in rangeConnection.RoundFires
on p.RangeActivityID equals r.RangeActivityID into sr
from x in sr.DefaultIfEmpty()
select new
{
TestName = p.TestName,
DateTime = p.ActivityDateTime,
Notes = p.Notes,
RoundSerialNumber = x.RoundSerialNumber,
RoundType = x.RoundType,
LotStockNumber = x.LotNumber
//consider checking for string.IsNullOrEmpty()
//for the RoundFires properties
};
The syntax for your entities may be inaccurate, but please edit my answer if it helps lead you to a solution.
I want to get table metadata for all table columns. Like type string(varchar2)/int/float/datetime and length for strings etc.
Cheers! -Matti
For all tables that you can access :
select * from all_tab_columns
For all tables in the current schema :
select * from user_tab_columns
This is specific to Oracle, but there is a more generic way to retrieve schema information : the DbConnection.GetSchema method :
schema_owner = "the_owner"; // or null
table_name = "the_table"; // or null
column_name = "the_column"; // or null
DataTable columns = connection.GetSchema("Columns", new string[] { schema_owner, table_name, column_name });
The resulting table contains all available column information that matches the criteria.
For a list of all available schema metadata, you can call GetSchema with DbMetaDataCollectionNames.MetaDataCollections as a parameter.
You can use the GetSchema method of the OracleConnection class.