Entity Framework - SqlQuery with List<> of parameters [duplicate] - c#

This question already has an answer here:
SQL "WHERE IN" query conversion to LINQ
(1 answer)
Closed 8 years ago.
I am trying to query the db with an IN clause using EF:
List<int> ids = new List<int> {1,2,3,4....20};
string sql = GetSql(ids);
//sql is "SELECT * FROM Student WHERE Id in (#p0, #p1, #p2 ... #p19)"
var res = db.Set<Student>().SqlQuery(sql, ids);
But I get the following exception :
No mapping exists from object type System.Collections.Generic.List`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] to a known managed provider native type.

I am handling in clause like this:
List<int> ids = new List<int> {1,2,3};
db.Set<Student>().Where(r => ids.Contains(r.ID));
UPDATE:
You do as follows (I have not tested by myself but it should do your job)
public List<CustomObject> ExecuteCustomQuery(List<int> items)
{
var ids = string.Join(",", items.Select(i => i.ToString()).ToArray());
string query = "SELECT Column1, Column1 FROM TABLE1 where id in (" + ids + ")";
return dbContext.Database.SqlQuery<CustomObject>(query).ToList();
}
CustomObject has got two properties of returning columns of select statement.
Let me know how did you go.
thanks.

Related

Insert record having field value based on the max value

I have a legacy sql that basically inserts record with subquery like this
INSERT INTO invoice (invno, otherfields )
VALUES ( (SELECT Max(invno)+1 AS maxinvno FROM invoices) , othervalues )
I'm trying to implement the same in C#'s NHibernate.
My question is:
Is it possible to avoid the SQL/HQL query and use LINQ NHibernate style instead. If possible - how to do that?
for example:
Invoice invoice = new Invoice();
invoice.invno = ...
session.save
update: stroke out the linq reference
update: added snippet with wanted result
***** In linq you can try this*****
using (AccountingDbContext dbContext = new AccountingDbContext())
{
Transaction objEmp = new Transaction();
objEmp.VoucherNo = ((from transction in dbContext.Transactions
select transction.Id).Max() + 1).ToString();
objEmp.TransactionType = "Payment";
dbContext.Transactions.Add(objEmp);
dbContext.SaveChanges();
}

How to add column in SELECT statement dynamically in tSQL based on condition?

I am creating a tSql with parameters and based on some condition I want to add column in SELECT statement and I am not sure how to do it.
My Logic:
var keywordClause = keyword.IsNotEmpty()
? "[Name] like '%" + keyword + "%'"
: "1 = 1";
// keywordClause = "[Name] like '%Test%'"
var orderBy = sortParameters.ToOrderBy();
// orderBy = "Name ASC"
var parameters = new List<SqlParameter>
{
new SqlParameter("#Keyword", keywordClause),
new SqlParameter("#OrderBy", orderBy)
};
var sql = string.Format(#"SELECT Id,
Name,
CreateDateTime Created
FROM CallCenter WITH (NOLOCK)
WHERE(IsDeleted = 0)
AND #Keyword
ORDER BY #OrderBy");
return _PageList(ctx => ctx.CallCenterSummaries.SqlQuery(sql, parameters.ToArray())
.AsQueryable()
.Select(d => d.TrimSpaces()), page, pageSize);
Based on my logic, I am expecting this query:
SELECT Id,
Name,
CreateDateTime Created
FROM CallCenter WITH (NOLOCK)
WHERE(IsDeleted = 0)
AND [Name] like '%Test%'
ORDER BY Name ASC;
Here I am getting "An expression of non-boolean type specified in a context where a condition is expected, near 'ORDER'." exception and I believe it is taking Name as a string. How can I get desired results?
You can't have SqlParameter as an entire clause - it needs to be right hand side of the clause. For your scenario - the below should work.
var parameters = new List<SqlParameter>
{
new SqlParameter("#Keyword", keyword.IsNotEmpty() ? keyword : "%")
};
var sql = string.Format($#"SELECT Id,
Name,
CreateDateTime Created
FROM CallCenter WITH (NOLOCK)
WHERE(IsDeleted = 0)
AND [Name] like #Keyword
ORDER BY {orderBy}");
EDIT:
I've edited my code sample to use order by as a value in the interpolated string rather than as a SqlParameter, however, this does open you up to a Sql injection if the value of the orderBy is influenced by user's inputs.
Alternatively, I would recommend not using ORDER BY clause at all in your query and sorting results in memory before passing them back for display.

select * where id= {multiply values) [duplicate]

This question already has answers here:
How to pass an array into a SQL Server stored procedure
(13 answers)
Closed 8 years ago.
I have a list List<Int32> containing ids and want to select some values from another table where id=ids[0],ids[1],...
it look like this:
string query=String.Format("# SELECT values from Table WHERE id=???");
How to get result?
P.S. as i listen- that this way is not right.
So, another way to do that- use Join:
string queryString = String.Format(#" SELECT * FROM Table1 [t1]
join [Table2] [t2]
on [t1].idTable1=[t2].id where [idParamValue]={0}", idParamValue);
So, then i should use :
using (var sqlCmd = new SqlCommand(queryString, _connection))
{
using (var sqlReader = sqlCmd.ExecuteReader())
{
while (sqlReader.Read())
{
var param1=(String)sqlReader["param_name"];
}
}
}
Thank you!
SELECT * FROM Table WHERE id IN (79,86,42)
You can use below query :-
string query=String.Format("# SELECT values from Table WHERE id in(value1,value2,value3,value4,...)");

Delete rows from mysql server from a list of ID's C#

I'm trying to delete a series of rows in a MySQL table from a list of ID's in C#. There's an employeeID row in the table. Basically my question is what kind of syntax would I use?
You would probably use an IN clause in your DELETE:
DELETE FROM `EmployeeTable` WHERE EmployeeID IN (2, 3, 4, 5, ...)
This could be implemented with the String.Join method to generate the list:
var query = "DELETE FROM `EmployeeTable` WHERE EmployeeID IN (" +
String.Join(",", myArray) + ")";
If you are using Dapper it would look something like this:
int[] ids = new int[]{1,2,3};
DbConnection cn = ... //open connection here
cn.Execute("delete from Employee where employeeID in #ids", new {ids});
delete from employee where employeeId in( 2,4,3,2,34 )

How to compare List<String> to DB Table using LINQ

I have a list<> of phone numbers and I am trying to join that with the corresponding records in the db table and get an order number and a customer ID. Also the list has the whole number as one string and the DB has it broken to area code, prefix, number each as separate fields.
I am fairly new to LINQ, so this is a beyond what I currently know. Any suggestions are GREATLY appreciated.
var tnbrs = new List<string>();
have tried:
var tntable = tnbrs.Cast<DataSet>();
var tntable = tnbrs.AsQueryble();<code>
var custdata = from c in db.CUSTs
join t in tntable on c.NPA + c.NXX + c.LINE_NBR equals t.???
select new { c.PON, c.PartnerID };
You dont have to cast tnbrs to dataset
try this instead
var custdata = from c in db.CUSTs
where tnbrs.Contains(c.NPA + c.NXX + c.LINE_NBR)
select new { c.PON, c.PartnerID };
It generates sql query something like this
SELECT [t0].[PON], [t0].[PartnerID]
FROM [dbo].[CUSTs ] AS [t0]
WHERE [t0].[NPA]) + [t0].[Nxx] + [t0].[LINE_NBR] IN (#p0, #p1)

Categories