linq mysql query into int array - c#

I'm still very new in my linq skills. I have a mysql query that returns 3 records, each record is an int. I want to stick those ints into an array. I thought I could make it easy on myself and do that with a linq command instead of creating a reader and looping through the results.
Here is my code:
query = "SELECT cic.catid FROM cart_item ci LEFT JOIN cart_item_category cic USING (itemref) WHERE ci.pid = #pid";
try
{
item.catIDs = con.Query(query, new { pid = ImId}).ToArray();
}
catch(MySqlException ex)
{
}
I am getting the error: Cannot implicitly convert type 'dynamic[]' to 'int[]'
I'm assuming my linq query is not correct.

Instead of using
con.Query(...
try using
con.Query<int>(...

Look like catIds is array of integer, But you are trying to assign anonymous collection to integer which is not correct.
Please try the below code. I think it should work
query = "SELECT cic.catid FROM cart_item ci LEFT JOIN cart_item_category cic USING (itemref) WHERE ci.pid = #pid";
try
{
item.catIDs = con.Query(query, Convert.ToInt32(ImId)).ToArray();
}
catch(MySqlException ex)
{
}

Related

Passing a list of int to dapper with mySQL

I have a current working solution that is doing a new db call for each project Id in a list and I am trying to do a single call instead that returns data from multiple projects.
To do this I am trying to pass a list of project Id's into a Dapper Query that hits a MySQL database. I either get an error of operand should contain 1 column(s) or I get the first result back and not one per projectId that is in the database.
The current c# code I am using is
public List<ProjectPortalManager> GetPPTech(IEnumerable<int> projIds)
{
string sql = #"SELECT tProject.ProjectID,
tProject.ProjectName,
tProject.PMUserID,
if(cast(tproject.dateinit as char) = '0000-00-00 00:00:00',null,tproject.dateinit) as DateInit,
tproject.comments,
tproject.ProjectNumber,
c.LName,
c.FName,
c.orgid,
c.orgname as organization,
c.Email,
c.Phone
From tProject left Join tContacts c on tProject.PMUserID = c.UserId
Where tProject.ProjectID in (#ProjIds);";
try
{
List<ProjectManager> pms = Conn.Query<ProjectManager>(sql, new { ProjIds = new[] { projIds } }).ToList();
return pms;
}
catch (Exception ex)
{
ErrorReport.ReportError(ex);
}
return new List<ProjectPortalManager>();
}
This does not error out but returns 0 results. When running the query in MySQL Workbench I do get one result back. However I am expecting several results. The SQL I run in workbench is:
SET #projIds = ('28, 99, 9');
SELECT tProject.ProjectID,
tProject.ProjectName,
tProject.PMUserID,
if(cast(tproject.dateinit as char) = '0000-00-00 00:00:00',null,tproject.dateinit) as DateInit,
tproject.comments, tproject.ProjectNumber,
c.LName,
c.FName,
c.orgid,
c.orgname as organization,
c.Email,
c.Phone
From tProject left Join tContacts c on tProject.PMUserID = c.UserId
where tProject.ProjectID IN (#projIds);
I have verified that all the Id numbers used do exists in the database.
There seems to be conflicting information online about how to do this but I have not found a solution that seems to work.
Don't put parentheses around the IN if you want Dapper to expand it to a list of parameters and populate them
where tProject.ProjectID IN #PIDs
Suppose you'd passed an array of size 3 in new { PIDs = projIds.ToArray() } - Dapper would effectively transform your SQL to:
where tProject.ProjectID IN (#PIDs1, #PIDs2, #PIDs3)
then behave as if you'd passed new { PIDs1 = projIds[0], PIDs2 = projIds[1], PIDs3 = projIds[2] }

How should I pass an array to the FIELD statement using Dapper, c#

I am trying to pass an array as a parameter using Dapper.
My array of values must go into the FIELD section.
I tried to join the array elements into a String and pass it. Still doesn't work.
Guid[] myArr = Ids.ToArray(); // Ids are List<Guid>
var script = #"SELECT * FROM table WHERE Id in #Ids ORDER BY FIELD(Id, #param)";
using (var connection = database.Connection)
{
return connection.Query<MyDataType>(script, new {Ids = Ids, param = myArr}).ToList();
}
This query is just doing an Order By Id. I also passed in param = Ids. Still doesn't work.
Convert the list into array in parameter list of dapper.
var sqlQuery = "Select * from table Where Columnname IN #periodIdStr";
var result = dapperUOW.Connection.Query<Entity>(sqlQuery ,
param: new { periodIdStr = periodIds.ToArray() }, transaction: dapperUOW.Transaction).ToList();
According to this question SELECT * FROM X WHERE id IN (...) with Dapper ORM you should be able to do a WHERE in with dapper but the limit of the number of items in the array is something to watch out for.
Then you could also break out the ORDER BY FIELD SQL and use linq to do an OrderBy on your results.
Edit:
Would this work?
Guid[] myArr = Ids.ToArray(); // Ids are List<Guid>
var script = #"SELECT * FROM table WHERE Id in #Ids)";
using (var connection = database.Connection)
{
var myDataTypeObjects = connection.Query<MyDataType>(script, new {Ids = Ids}).ToList();
myDataTypeObjects = myDataTypeObjects.OrderBy(x => Ids.IndexOf(x.Id)).ToList();
return myDataTypeObjects;
}

How to store a sql result to a variable in C# using Dapper.NET

I'm using dapper in my project, a beautiful tool for storing the SQL query results to a List and this working good.
I wrote a SQL query to fetch a record from database and store the result in a variable, I tried using dapper but stuck up with an error. I've pasted the corresponding code.
Exception: Unable to cast object of type
'System.Collections.Generic.List`1[Dapper.SqlMapper+DapperRow]' to
type 'System.IConvertible'.
try
{
using(var connection = ...)
{
connection.Open();
const string masterSelectQuery = "SELECT Id as [fileId], FileName as [fileName], Frequency as [frequency], Scheduled_Time as scheduledTime FROM MASTER_TABLE";
masterTableList = connection.Query<MasterTableAttributes>(masterSelectQuery).ToList();//Working fine
const string lastProcessedTimeQuery = "SELECT TOP 1 file_transfered_time as [lastProcessedTime] FROM PROCESS_LOGS ORDER BY file_transfered_time DESC";
DateTime lastProcessedTime = Convert.ToDateTime(connection.Query(lastProcessedTimeQuery)); //Here it fails
}
}
To overcome this error I used SQLCommand as follows
using (command = new SqlCommand(lastProcessedTimeQuery, connection))
{
DateTime lastProcessedTime = (DateTime)command.ExecuteScalar();//working fine
}
I am making a mistake in using dapper, can anyone please guide me?
Thanks in advance.
connection.Query(lastProcessedTimeQuery) returns a sequence of rows, each individually dynamic. Assuming file_transfered_time is a datetime, you have two choices here:
DateTime lastProcessedTime = connection.Query<DateTime>(
lastProcessedTimeQuery).Single();
or, to show how non-generic Query works with a dynamic row:
DateTime lastProcessedTime = connection.Query(
lastProcessedTimeQuery).Single().lastProcessedTime;
If your PROCESS_LOGS table could ever be empty, you might prefer SingleOrDefault:
DateTime? lastProcessedTime = connection.Query<DateTime?>(
lastProcessedTimeQuery).SingleOrDefault();
or:
var row = connection.Query(lastProcessedTimeQuery).SingleOrDefault();
DateTime? lastProcessedTime = null;
if(row != null) lastProcessedTime = row.lastProcessedTime;

Converting this SQL to LINQ

I have the following SQL statement to be converted into LINQ in C#. The #amount variable will be a C# variable.
DECLARE #amount DECIMAL(20,2)
SET #amount = 120.30
UPDATE INVOICES SET AmtPaid = AmtPaid + #amount WHERE InvoiceNum = 'AC0000034550'
You cannot UPDATE with LINQ.
LINQ is a query engine, suitable for SELECT (if we talk in terms of raw SQL).
Plus, if you already have good working SQL code, it does not make any sense to convert it into LINQ; SQL is faster, and works.
why dont you make a select with linq an then iterate over the list and update the variable??
LINQ does not do updates,so you cannot convert the SQL to LINQ
I did as follows. Not sure whether it is correct or not:
using (var dataContext = GetDataContext())
{
var invoiceData = from i in dataContext.Invoices
where i.InvoiceNumber == paymentData.InvoiceNumber
select i;
foreach(var invoice in invoiceData)
{
decimal outPut;
if (Decimal.TryParse(paymentData.AmountPaid, out outPut))
{
invoice.AmtPaid = invoice.AmtPaid + Convert.ToDecimal(paymentData.AmountPaid);
}
}
dataContext.SubmitChanges();
}

How can I directly execute SQL queries in linq

In C# with VS 2008,I have a query ,In this query i join more than one tables,so i don't know the type , I want to know how to directly run a sql query in linq .
IEnumerable<Type> results = db.ExecuteQuery<TYpe>("sql query")
My above query works fine but I want to avoid type, I want to write
var results = db.ExecuteQuery("sql query");
Is there any way to write it?
Thanks in advance.
var result = dataContext.ExecuteQuery<JobsDto>
("Select JobID,JobName From jobs");
but make sure JobsDto has two properties JobID and JobName and there types the same type as the table columns
PS. DTO stand for Data Transfer Object
You need to specify the type to map to from the query results. You can use a System.Type object instead of statically specifying it as a generic type parameter:
var results = db.ExecuteQuery(typeof(Customer), "sql query ");
If you just want a plain ADO.NET DataReader you could use the DataContext.Connection property:
using (var cmd = db.Connection.CreateCommand())
{
cmd.CommandText = "sql query ";
var results = cmd.ExecuteReader();
}

Categories