Automapper to read single record - c#

I have been trying to read single Record using AutoMapper. But I couldn't get through using the below code,
public ChartOfAccount GetSingleCOA( )
{
string queryString = "select * from ChartofAccounts where AccNo=423";
using (var connection = new SqlConnection(conStr))
using (var command = new SqlCommand(queryString, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
if (reader.HasRows)
{
reader.Read();
return Mapper.Map<IDataRecord, ChartOfAccount>(reader);
}
}
return null;
}

simply changing the line to
return Mapper.DynamicMap<IDataReader, ChartOfAccount>(reader);
solved the issue

Related

Refering to view values one by one

I have the following code which establishing an SQL connection inside of a project I am working on. What I want to do is to create a for loop which contains a method and every time the loop repeats the method runs with a different value until all views of the returned query are used.
I can't figure out how to refer to every value of the view without saving the view to a list or an array first. Any ideas?
SqlConnection Con = new SqlConnection(#"Data Source=localhost\**;Initial Catalog=ML;User Id=sa;Password='**'");
string sql = #"select product_id,Name from E_PRODUCT_PROPERTY";
var mylist = new List<WineRating>();
using (var command = new SqlCommand(sql, Con))
{
Con.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
new WineRating { product_id = reader.GetInt32(0), Name = reader.GetString(1) };
///Here goes the code I suppose
method_name(reader.GetInt32(0), reader.GetString(1));
}
}
public static int method_name(int product_id, string Name)
{
int num = x *2;
Console.WriteLine(num + Name);
}
Perhaps like this:
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
MyMethodToPrintToScreen(reader.GetInt32(0), reader.GetString(1));
}
}
With the method to print to screen
private static void MyMethodToPrintToScreen(int id, string product)
{
//Do whatever you wish with the data: example
Console.WriteLine($"My id: {id} | Product: {product}");
}
Edit
Let me make it even more obvious(using your exact code):
SqlConnection Con = new SqlConnection(#"Data Source=localhost\**;Initial Catalog=ML;User Id=sa;Password='**'");
string sql = #"select product_id,Name from E_PRODUCT_PROPERTY";
var mylist = new List<WineRating>();
using (var command = new SqlCommand(sql, Con))
{
Con.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
method_name(reader.GetInt32(0), reader.GetString(1));
}
}
}

Single DBDataRecord From DataReader

I am using the following generic data helper function to run queries and return them as a collection of DbDataRecords.
public static IEnumerable<DbDataRecord> GetDataRecords(string Query, Dictionary<string, object> Parameters, CommandType CommandType = CommandType.Text)
{
using (MySqlConnection Connection = CreateConnection())
{
using (MySqlCommand cmd = new MySqlCommand(Query, Connection))
{
cmd.CommandType = CommandType;
foreach (var Parameter in Parameters)
{
cmd.Parameters.AddWithValue(Parameter.Key, Parameter.Value);
}
Connection.Open();
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
foreach (DbDataRecord record in Reader)
{
yield return record;
}
}
Connection.Close();
}
}
}
This works great for multiple results, but I'd also like to create a function that returns a single record from the reader as a single DbDataRecord. What I cant figure out is how to convert a single row from a reader into a DbDataRecord. Here is what I have so far:
public static DbDataRecord GetDataRecord(string Query, Dictionary<string, object> Parameters, CommandType CommandType = CommandType.Text)
{
DbDataRecord Record = null;
using (MySqlConnection Connection = CreateConnection())
{
using (MySqlCommand cmd = new MySqlCommand(Query, Connection))
{
cmd.CommandType = CommandType;
foreach (var Parameter in Parameters)
{
cmd.Parameters.AddWithValue(Parameter.Key, Parameter.Value);
}
Connection.Open();
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
if(Reader.Read() != false)
{
Record = ???;
}
}
Connection.Close();
}
}
return Record;
}
I have seen lots of examples that show how to return one column (ExecuteScalar), that is not what I am looking for. I also know how to get individual column values. Again, that is not what I am looking to do.
Basically I want to be replace the following foreach loop
foreach (DbDataRecord record in Reader)
{
yield return record;
}
with something that converts a single reader row into a DBDataRecord
You could return IDataRecord instead, that could be sufficient, then you can return the MySqlDataReader directly. Or you have to cast it accordingly:
So this is not possible directly:
Record = (DbDataRecord)Reader;
but in this way:
Record = (DbDataRecord)(IDataRecord)Reader;

How to return a MySqlDataReader before the reader is closed [duplicate]

This question already has answers here:
Return DataReader from DataLayer in Using statement
(4 answers)
Closed 10 years ago.
Okay, my code is currently:
public MySqlDataReader CreateQuery(string queryString, string connectionString )
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
MySqlDataReader reader = command.ExecuteReader();
return reader;
}
}
}
In another function, I've got:
using(MySqlDataReader readers = _connection.CreateQuery(query, connectString))
Currently, in this form, when I return reader into a readers, there is no value. I've stepped through, and verified that at the point of the return, reader had the correct information in it. Yet readers has no values. I'm probably missing something completely silly. But any and all help in this will be appreciated. Thanks!
With the using command, your code is actually going to dispose of the connection and the command before control is returned to the caller. Essentially your connection object and your command object created in the using statements are disposed before the calling code is able to use it so its no longer usable.
You probably want to do something with the results of the query rather than the reader itself. Perhaps load it into a table? Something like:
public DataTable CreateQuery(string queryString, string connectionString )
{
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}
return results;
}
Instead of returning the Datareader or copy all records into an in-memory DataTable that you return as a whole, you could return an IEnumerable<IDataRecord> which is the basic interface a DataReader record implements.
So this should work since the yield causes the Connection to keep alive:
public IEnumerable<IDataRecord> CreateQuery(string queryString, string connectionString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return (IDataRecord)reader;
}
}
}
}
}
If you want for example take only the first 5 records:
var records = CreateQuery("SELECT * FROM ais.country;", Properties.Settings.Default.MySQL).Take(5);
foreach (IDataRecord rec in records)
{
String country = rec.GetString(rec.GetOrdinal("Name"));
}

How can I populate a list with values from a SQL Server database?

The list will grow and shrink depending on how many items I have in my database.
I need to populate a list not a listbox. I understand I will need to open a connection.
using (var conn = new SqlConnection(Properties.Settings.Default.DBConnectionString))
{
using (var cmd = conn.CreateCommand())
{
conn.Open();
List<string> TagList = new List<string>();
for (int i = 0; i < TagList.Count; i++)
TagList[i].Add("Data from database");
cmd.ExecuteNonQuery();
}
}
I'm really not sure how to do this and I'm sure my method up here looks very wrong so I really need help.
Could someone show me what I'm doing wrong?
public IEnumerable<string> GetTagList()
{
using (var connection = new SqlConnection(Properties.Settings.Default.DBConnectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "select Tag from TagsTable"; // update select command accordingly
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return reader.GetString(reader.GetOrdinal("Tag"));
}
}
}
}
then you can call it as below
List<string> tags = GetTagList().ToList();
I would like to share my solution, hope helps someone in the future:
public List<string> getFromDataBase()
{
List<string> result = new List<string>();
using(SqlConnection con = new SqlConnection("connectionString"))
{
con.Open();
DataTable tap = new DataTable();
new SqlDataAdapter(query, con).Fill(tap);
result = tap.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("columnName")).ToList();
}
return result;
}
This would do as it is (if I didn't do any typos...)
private void LoadList()
{
List<string> tagsList = new List<string>();
using (IDbConnection connection = new SqlConnection(Properties.Settings.Default.DBConnectionString))
{
connection.Open();
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT TAGCOLUMN FROM TAGSTABLE";
using (IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (!reader.IsDBNull(0))
tagsList.Add(reader.GetString(0));
}
reader.Close();
}
}
connection.Close();
}
}
EDIT:
Of course you have to change the select statement to the correct one from your database.
I just used a pseudo one to show you what to put there.

Get database list in Npgsql

How can I get a list of all available PostgreSQL databases on a user's computer using Npgsql in C#?
In postgreSQL there are two way to do it :
\l
SELECT datname FROM pg_database;
Using Npgsql You can use such code snippet:
IEnumerable<string> GetDatabaseNames()
{
var connStrBuilder = new NpgsqlConnectionStringBuilder();
connStrBuilder.Host = "localhost";
connStrBuilder.Username = "theduck";
connStrBuilder.Password = "password123";
connStrBuilder.Database = "postgres"; // this database is always present
using (var conn = new NpgsqlConnection(connStrBuilder.ConnectionString))
{
conn.Open();
using (var command = new NpgsqlCommand("SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname;", conn))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return reader.GetString(0);
}
}
}
}

Categories