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();
}
Related
I'm trying to retrieve all fields from two joined tables to any kind of a c# object.
So I'm trying to run this code:
var query = #$"EXEC('select *
from persons p join students s on p.id=s.id
where p.id = 21')";
var result = _context.Database.SqlQuery<?>(query).ToList();
But I don't get what should be instead of the question mark.
I've tried List<object> and Dictionary<string,string> but since I couldn't get exactly how this is being mapped, I don't understand to what it can be mapped.
There is a somewhat similar question here but its solution only addresses two columns, and it apparently doesn't support returning nulls.
You can try creating a stored procedure or a function in the SQL level.
Then, just select then generated table / result.
So, you already have an idea of what class it is.
I frequently use the dynamic type like this :
var lst = _context.Database.SqlQuery<dynamic>(query).ToList();
foreach (var item in lst)
{
var myVar = item.myfieldName;
}
It may be preferable to name each field in your query instead of using select *.
Hi I am trying to write linq query to get some details from Sql table. I have created column and storing date and time both. while returning i want to ommit time part. May I know is this possible?
List<returnObject> obj = new List<returnObject>();
obj = (from c in objectDB.NCT_Project
join user in objectDB.NCT_UserRegistration on c.adminUserId equals user.User_Id
where c.adminUserId == userId
select new returnObject
{
id = c.project_Id,
key = c.key,
created = c.createdDate //currently returns datetime
}).ToList();
Any help would be appreciated. Thank you.
Use DbFunctions.TruncateTime method:
created = DbFunctions.TruncateTime(c.createdDate)
According to the docs:
When used as part of a LINQ to Entities query, this method invokes the
canonical TruncateTime EDM function to return the given date with the
time portion cleared.
All you need to do is call 'Date' property on createdDate.
select new returnObject
{
id = c.project_Id,
key = c.key,
created = c.createdDate.Date
}).ToList();
you can try this one.
created = c.createdDate.ToString("HH:mm")
created = c.createdDate.ToString("H:mm")
created = c.createdDate.ToString("hh:mm tt")
created = c.createdDate.ToString("h:mm tt")
also see this question : How to get only time from date-time C#
If you can get date comparison out of the LINQ and leave the rest there, you can use this syntax:
sqlite.Query<Entity>("date comparison").Where("other queries")
The predicate I used in the Query() function had to return only todays orders and looked something like this:
select * from Order where date(orderDate/ 10000000 - 62135596800, 'unixepoch') = date('now')
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)
{
}
This question already has answers here:
List of tables used in an SQL Query
(5 answers)
Closed 9 years ago.
I need extract from simple string that represent an sql query the tables that are used on the query without execute the query itself in C#.
Example:
string strQuery = "SELECT * FROM table1 LEFT JOIN (SELECT * FROM table2) tt WHERE tt.name IN (SELECT name FROM table3)";
ArrayList arrUsedTables = GetUsedTablesFromQuery(strQuery);
and after this line the object arrUsedTables would contain:
table1,table2,table3
Remember that the query may be much complicated!
Without going to the DB you can't know for certain the names of the tables used in the query.
What if your query uses a view or a stored procedure?
Without consulting the database, these are transparent to the consumer.
The only way to be certain is to query the list of the tables from the database and then to attempt to parse them from your inline sql.
You will have to add references and directives for the following assemblies:
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
using System.IO;
Then, you may create the GetUsedTablesFromQuery method:
private static ArrayList GetUsedTablesFromQuery(string strQuery)
{
var parser = new TSql100Parser(true);
IList<ParseError> errors = new List<ParseError>();
using (TextReader r = new StringReader(strQuery))
{
var result = parser.GetTokenStream(r, out errors);
var tables = result
.Select((i, index) => (i.TokenType == TSqlTokenType.From) ? result[index + 2].Text : null)
.Where(i => i != null)
.ToArray();
return new ArrayList(tables);
}
}
You can certainly use a SQL parser such as ANTLR, as described in this question and answer, in order to get a full parse of the SQL, and then extract the table names.
Another option is to execute some raw SQL to get the execution plan of the query (using the instructions here). The execution plan is in XML, and then you can use Linq to XML to query the plan for all Table attributes on any ColumnReference tag.
I a have a simple linq to sql query and for some reason the .take() doesn't work. I tried to add skip() as well thinking that maybe it needed some starting point from where to take the records but the results are still same and rather than taking only 10 records, it takes all 240 records.
Would appreciate if somebody can tell me what's going on. Thanks in advance.
The code is:
var types = (from t in EventTypes.tl_event_types
select new
{
type_id = t.event_type_id,
type_name = t.type_name
}).Take(10);
I'm assuming that by naming conventions that EventTypes is your object. You need to select from your data context... So
var types = (from t in dataContext.EventTypes.tl_event_types
select new
{
type_id = t.event_type_id,
type_name = t.type_name
}).Take(10);
should work.