Get column by table name entity framework reflection - c#

I need to get column name and value from a table which I know only the name.
I try lot of stuff but without success.
I use this for get my table :
var table = oSession.ctx.GetType()
.GetProperty("country")
.GetValue(oSession.ctx, null);
I'm lock with that I can't retrieve the informations of my columns ..
Perhaps I have already try this :
List<string> columnsNames = table.GetType().GetFields().Select(field => field.Name).ToList();
Thx for your help..

Use ((IQueryable)table).ElementType.GetProperties() as a starting point. Also you can get some ideas from Dynamic LINQ query to get Field value from Database

you can probably try using GetProperties()
table.GetType().GetProperties().Where(p => !(p.GetMethod.IsVirtual || p.GetIndexParameters().Length > 0)).ToList()

Related

Get columns name from a table in database

in my database i have many of tables one of Tables is nambed Company". and its columns names are as follows ("ComName","ComAddress","ComType" ..etc)
I have a function which get the columns name from Company table :
public List<string> GetColumnNames(string tablename)
{
var names = typeof(Company).GetProperties().Select(p => p.Name).ToArray();
return names.ToList();
}
Until now everything is good but what if i want to get the columns of other tables ? so i have to put the name of the new table (that is given in the function as "tablename") instead of "Company" in this sentence :
var names = typeof(Company).GetProperties().Select(p => p.Name).ToArray();
but it is string so its not working. any idea ?
typeof(Company).GetProperties() isn't fetching the names of the columns of your table at all though - it's fetching the names of the properties of the C# class/entity that you're using to represent that table. Do you already have a process to guarantee you have C# entities with property names that exactly match the column names of your tables? If so, you can do the same principle (but instead of using typeof(Company) you'd need to find the type by name, which there are various ways of doing). If not, you'll need to to actually query the database to find the column names.
As far as i know, you can use the Type parameter.
public List<string> GetColumnNames(Type tablename)
{
var names = tablename.GetProperties().Select(p => p.Name).ToArray();
return names.ToList();
}

trying to replace a field name using a variable at run time in EF

Let me preface that I have searched this question and tried a ton of things but I am obviously missing something simple (I think).
I believe my solution will involve reflection but I just can't get it right.
Edit:
Quicker question - I need to replace the .fieldname of a query result with a string. So var value = stops.First().con_name; the .con_name needs to be dynamic at run time.
Basics:
I am creating the ability to generate custom reports from a database where the report layout is stored in a table of column names, column position and field names.
So the below is the data for a very simple report:
record 1
col_index - 17
field_name - con_name
record 2
col_index - 18
field_name- con_city
I am needing to query a table called stop_details for a collection of records that are to be included in the report.
I then want to query a table called report_matrix that will return the above records (the two sample records I gave).
I then need to step through the matrix results and create the columns based on the data.
The challenge is replacing the field_name at run time.
So in the below code on the first run through it would have var value = stops.First().con_name; the second time .con_name would be replaced with .con_city etc....
Here is my code:
//get collection of stops for export
var stops = (from s in db.stop_details
where s.eCourier_export_flag == true
select s)
.ToArray();
//pull in all the report format details
var reportLayout = (from r in db.report_matrix
where r.report_id == 1
select r)
.ToArray();
//just do one line
foreach (var layoutElement in reportLayout)
{
// Select the PropertyInfo of the column.
PropertyInfo propertyInfo =
stops.First().GetType().GetProperty(layoutElement.field_name);
// name = stops.GetValue(propertyInfo, null).ToString();
// HERE is where I need to replace .con_name with the field name from the query
var value = stops.First().con_name;
}
Thank you in advance for any help....
Joe
You need to use the GetValue method of PropertyInfo:
PropertyInfo propertyInfo =
stops.First().GetType().GetProperty(layoutElement.field_name);
var value = propertyInfo.GetValue(stops.First());

Selecting specific columns with Linq, using string or propertyInfo

I am rebuilding our reporting system using EF, where as our old system used a lot of dynamic SQL (bad i know), so i would like to do it using Linq, so it uses parameterized queries etc.
In a report a user can choose which columns of data they want to view. Now how can i take these values and return an SQL statement using Linq and get the columns i need? I wonder if i should even bother and just return all the data, then just show the columns the user wants on screen, which may be want i need to do, but thought i would ask anyway.
So lets take the following Linq example, i say i would only like the Id, Name and Town, how could i do this. Currently i have something similar to
var columns = new List<string>() { "Id", "Name", "Town" };
return _context.Data
.Where(e => e.Name == "test")
.ToList();
Is this even possible?
if you yant select propertys accordance their names try Dynamic LINQ library:
public List<Data> ListByNames(string[] arr)
{
var str = string.Format("new ({0})", string.Join(", ", arr));
return _context.Data.Select(str);
}
Or write your own Expression, see #TomBrothers answer: https://stackoverflow.com/a/4546633/1271037
I know this kind of problem. Chief problem: with EF you are not handling columns any more but properties.
Try somthing like this:
var column="yourcolumn";
return _context.Data.Where(e => e.GetType().GetProperty(column).GetValue(_context, null)).ToList();

Trying to update a DataRow in C# with LINQ

I'm trying to find, then update, a specific DataRow in a DataTable. I've tried a few things based on my searches, and the code below seems to be the closest I can get. The linq will return one row. With that row, I'd like to update column values (Status, StopTime, Duration). I can't for the life of me find how to do this.. I've tried casting, but I'm new to linq and don't see how to update these values.
private DataTable downloadProcStatusTable;
void UpdateDataDownloadProcedureList(ProcedureStats ProcStats)
{
var currentStatRow = from currentStat in downloadProcStatusTable.AsEnumerable()
where currentStat.Field<String>("ProcedureName") == ProcStats.ProcName
select currentStat;
}
Your query as it stands actually gives you an IEnumerable<DataRow>. You need to do this to get the actual row:
var currentStatRow = (from currentStat in downloadProcStatusTable.AsEnumerable()
where currentStat.Field<String>("ProcedureName") == ProcStats.ProcName
select currentStat).SingleOrDefault();
You should then be able to use the currentStatRow variable to modify the column values.
Outline
Load the existing entity from the database (unless you have one that you can re-attach, in which case you could avoid this additional query)
Update the properties as needed
Submit the changes back to the database using SubmitChanges()
Implementation
I wasn't exactly sure where your variables are and the names, but this should give you a good start...
void UpdateDataDownloadProcedureList(ProcedureStats ProcStats)
{
var currentStatRow = (from currentStat in downloadProcStatusTable.AsEnumerable()
where currentStat.Field<String>("ProcedureName") == ProcStats.ProcName
select currentStat).FirstOrDefault();
currentStatRow.Status = ProcStats.Status;
currentStatRow.StopTime = ProcStats.StopTime;
currentStatRow.Duration = ProcStats.Duration;
downloadProcStatusTable.SubmitChanges();
}

Dynamic LINQ in c#

Hey i am making a simple search machine through alot of different coloumns in 2 tables.
I was trying to get this to abit dynamical.
I read this:
Is there a pattern using Linq to dynamically create a filter?
Which is something that really could do the trick for me.. its just in VB and i need it in c#
here is my code :
private void displayWith1Criteria(string column, string value)
{
Console.WriteLine("entering _1_ display method");
dbcontent = new DBtestEntities();
var studienummerQuery = from members in dbcontent.Medlemmer.Include("Retninger")
where column == value
orderby members.Fornavn
select new { Studienr = members.Studienummer, Fornavn = members.Fornavn, Efternavn = members.Efternavn, Email = members.Email, Studiested = members.Studiested, Betaling = members.BetalingsType, Uddannelses_Retning = members.Retninger.retningNavn };
dataGridView1.DataSource = studienummerQuery;
}
Doesn't return any data at all...
column is being called with members.Fornavn (Fornavn - a column name)
value = Anders (one of the data's in Fornavn column)
What I want to do:
My database is loaded into dbcontent using a .edmx file from ABO entity class.
My database consist of 2 tables, "Retninger" and "Medlemmer".
Medlemmer contains columns things like Fornavn(in english, Firstname), Efternavn(Lastname), Studienummer(study no.)
What i would like is a "dynamic" method that can set both which column to be searched in and the value that needs to be searched for in the set column.
When could your expression column == value possibly return true? Only if string.Equals("Fornavn", "Anders") is true.
Doing dynamic linq is hard. Is usually do it this way:
...
where (!useMycolumn1 || member.mycolumn1 == value1)
&&(!useMycolumn2 || member.mycolumn2 == value2)
&&(!useMycolumn3 || member.mycolumn3 == value3)
...
useMycolumn* is a local boolean variable which is set to true or false, depending on whether the certain condition should be tested or not. This way, unused parts of the query are optimized out at compile time.
I think this answer from Shawn Miller to the question you linked is more what you are looking for:
http://www.albahari.com/nutshell/predicatebuilder.html
Are you remembring to call the DataBind() method on the grid? How do you know nothing is being returned?
I think its because of lazy evaluation of LINQ queries.
You can try using .ToList, as below:
dataGridView1.DataSource = studienummerQuery.ToList();
also .DataBind(), if relevant for your object.
Edit:
Lazy Evaluation: This Link, would serve as a good start

Categories

Resources