I have a working query that returns 140 rows from the db:
string tag = "New York";
string sql = "select " +
" T.Id TagId, " +
" PM.Id MachineId, " +
$" '{tag}' TagSiteName, " +
" T.Name TagCpeMachineLine, " +
" PM.Plant, " +
" PM.Line, " +
" PM.Type " +
"from Tags T " +
"inner join PaperMachines PM " +
" ON PM.Id = T.PaperMachineId " +
$"WHERE T.Name LIKE ( '{tag}' ) ";
var result = db.Database.SqlQuery<TagsMachines>(sql);
When I try to parameterize it, I get 'Enumeration yielded no results' from the result.
string tag = "New York";
string sql = "select " +
" T.Id TagId, " +
" PM.Id MachineId, " +
" '#tag' TagSiteName, " +
" T.Name TagCpeMachineLine, " +
" PM.Plant, " +
" PM.Line, " +
" PM.Type " +
"from Tags T " +
"inner join PaperMachines PM " +
" ON PM.Id = T.PaperMachineId " +
"WHERE T.Name LIKE ( '#tag' ) ";
var result = db.Database.SqlQuery<TagsMachines>(sql, new SqlParameter("#tag", tag));
I'm not sure what's going on here. Any ideas?
Remove the #tag from top of your Query and at the bottom of your Query make it
T.Name = #tag or T.Name like ('%' + #tag +'%') if you want like contains.
Finally at the end of the result line add a .FirstOrDefault().
Related
I had a code that was working the past few weeks and am getting an ERROR "Input string was not in a correct format"
NB:(MVC Asp.net)
the view gets data from the Razor page URL and Execute a query
the URL is like this: https://localhost:44348/Devices/Details/5?typeName=Dongle
and the following the View code :
public ActionResult Details(string typeName, int? id)
{
var sql = "SELECT A.*," +
" COALESCE(ps.first_name, '') as firstname," +
" COALESCE(ps.last_name, '') as lastname," +
" COALESCE(p.program_name, '') as program_Name, " +
" COALESCE(l.loan_date, '') as loan_date, " +
" COALESCE(l.return_date, '') as return_date" +
" FROM devices A" +
" LEFT JOIN device_loans l on l.device_id = A.device_id" +
" LEFT JOIN persons ps on ps.person_id = l.person_id" +
" LEFT JOIN programs p on A.program_id = p.program_id" +
" WHERE A.device_type = '" + typeName + "' and p.program_id = "+ id +";";
var devices = _context.DeviceDetails
.FromSqlRaw(sql)
.ToList();
return View(devices);
}
I have tried Passing parameters with parameter placeholders but still not working
please help.
Because your parameter id: is nullable, you need combine sql like:
var sql = "SELECT A.*," +
" COALESCE(ps.first_name, '') as firstname," +
" COALESCE(ps.last_name, '') as lastname," +
" COALESCE(p.program_name, '') as program_Name, " +
" COALESCE(l.loan_date, '') as loan_date, " +
" COALESCE(l.return_date, '') as return_date" +
" FROM devices A" +
" LEFT JOIN device_loans l on l.device_id = A.device_id" +
" LEFT JOIN persons ps on ps.person_id = l.person_id" +
" LEFT JOIN programs p on A.program_id = p.program_id" +
" WHERE A.device_type = '" + typeName + "'";
if(id!=null){
sql += " and p.program_id = "+ id +";";
}
BTW: your code has SQL injection risk
I am getting the following error trying to query from my database using C#:
LINQ to Entities does not recognize the method 'MyProject.Models.DB.Department getDepartment()' method, and this method cannot be translated into a store expression.
In my controller I have:
var query = db.Activities.AsQueryable();
query = query.Where(x => rs.department.Contains(x.getDepartment().id));
In my model I have the following method which returns the correct Department for an Activity. I know the problem is that I am executing the query when I do the .First(), but I can't find a way to return this as a IQueryable result:
public partial class Activity
{
public Department getDepartment()
{
return db.Departments.SqlQuery( "" +
"SELECT * FROM " +
"[snt].[Departments] " +
"INNER JOIN( " +
"SELECT " +
"[Users].departments_id AS id " +
"FROM " +
"[snt].[Users], " +
"[snt].[People], " +
"[snt].[EventPerson], " +
"[snt].[EventPersonTask], " +
"[snt].[Tasks], " +
"[snt].[Events], " +
"[snt].[Activities] " +
"WHERE " +
"[snt].[Activities].id = {0} AND " +
"[snt].[Events].id = [snt].[Activities].events_id AND " +
"[snt].[EventPerson].events_id = [snt].[Events].id AND " +
"[snt].[EventPerson].people_id = [snt].[People].id AND " +
"[snt].[EventPersonTask].tasks_id = [snt].[Tasks].id AND " +
"[snt].[EventPersonTask].eventperson_id = [snt].[EventPerson].id AND " +
"[snt].[Tasks].name = 'owner' AND " +
"[snt].[Users].is_active = 1 AND " +
"[snt].[Users].people_id = [snt].[People].id" +
" ) AS x " +
"ON " +
"x.id = [Departments].id", this.id).First();
}
}
below is my Query and i am getting the Error:
query references a field that does not exist. The error is caused by «[Microsoft.VSTS.Common.Priorty]».'
string querystring = string.Format("select [System.Id], [System.WorkItemType]," +
" [System.Title],[System.State],[System.AssignedTo]," +
"[Microsoft.VSTS.Scheduling.StoryPoints]," +
"[Microsoft.VSTS.Common.Priority],[System.IterationPath]" +
" FROM WorkItemLinks" +
" WHERE" +
" ([Source].[System.TeamProject]='{0}'" +
" and [Source].[System.IterationPath]='MRI_SCRUM_GIT\\Pluse Pheonix\\Sprint 1'" +
" and (Source.[System.WorkitemType]='User Story' " +
" or [Source].[System.WorkitemType]='Task'))" +
" and [System.Links.LinkType]='System.LinkTypes.Hierarchy-Forward'" +
" and [Target].[System.WorkItemType] <> '' " +
" ORDER BY [Microsoft.VSTS.Common.StackRank]," +
" [Microsoft.VSTS.Common.Priorty]" +
" mode (Recursive)", projectname);
Query treequery = new Query(workItemStore, querystring);
WorkItemLinkInfo[] links = treequery.RunLinkQuery();
Replace [Microsoft.VSTS.Common.Priorty] to [Microsoft.VSTS.Common.Priority] in ORDER By statement.
I have a query in my Asp.net project, which create two table and then insert amount of date into it, when there are afew data so there is no problem, it is my query :
protected void btnLottryInformationSave_Click(object sender, EventArgs e)
{
try
{
int rowCount;
var finalTempTableName = FindTableName();
var selecterServicesList = cblServices.Items.Cast<ListItem>().Where(x => x.Selected).ToList();
var selectedServices = selecterServicesList.Aggregate(string.Empty, (current, service) => current + ("'" + service.Value + "',")).TrimEnd(',');
var tempTableName = "Temp_" + finalTempTableName;
var drawQuery = " if (OBJECT_ID('Temp.dbo." + tempTableName + "') is not null) \ndrop table Temp.dbo." + tempTableName + ";\n";
drawQuery += " create table Temp.dbo." + tempTableName + "(Number char(11) primary key,RepCount int);\n";
drawQuery += " if (OBJECT_ID('Temp.dbo." + finalTempTableName + "') is not null) \ndrop table Temp.dbo." + finalTempTableName + ";\n";
drawQuery += " create table Temp.dbo." + finalTempTableName + "(Id int identity(1,1) primary key,Number char(11));\n";
drawQuery += " select org.orig \n" +
" into #MoOrig \n" +
" from VSReceiveSend.dbo.OrigPrices org \n" +
" INNER JOIN VSReceiveSend.dbo.Services s on (s.Orig = org.Orig) \n" +
" where s.Code in (" + selectedServices + ") and org.MTPrice <> 0 \n ";
if (drpLotteryType.SelectedValue == "1" || drpLotteryType.SelectedValue == "2")
{
drawQuery += " INSERT INTO Temp.dbo." + tempTableName + " (Number,RepCount)\n" +
" select number," + (drpLotteryType.SelectedValue == "1" ? "1" : "sum(c) ") +
" from (\n" +
" SELECT Number,COUNT(*) c \n" +
" FROM VSReceiveSend.dbo.ReceivedSMS with(nolock)\n" +
" INNER JOIN VSReceiveSend.dbo.#MoOrig org ON (org.Orig = ReceivedSMS.Orig) \n " +
" WHERE Date BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' \n" +
" GROUP BY Number\n" +
" union all \n " +
" SELECT Number,COUNT(*) c \n" +
" FROM VSReceiveSend.dbo.SentSMS with(nolock) \n" +
" INNER JOIN VSReceiveSend.dbo.OrigPrices org ON (org.Orig = SentSMS.Orig AND org.MTPrice <> 0 ) \n " +
" WHERE SentDate BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' AND SentSMS.ServiceCode in (" + selectedServices + ") \n" +
" GROUP BY Number \n" +
" ) DerivedTable \n" +
" group by number \n" +
((drpLotteryType.SelectedValue == "2" && txtMinAnswerCount.Text != "") ? "HAVING sum(c) >= " + txtMinAnswerCount.Text : "") + ";\n";
}
else if (drpLotteryType.SelectedValue == "3")
{
var pointCount = int.Parse(txtMinCustomerPoint.Text);
drawQuery += " INSERT INTO Temp.dbo." + tempTableName + " ( Number,RepCount)\n" +
" SELECT Number,SUM(Point) / " + txtDivPoints.Text + " RepCount " +
" FROM VsReceiveSend.dbo.SubscriberMatchHistory with(nolock) \n" +
" where ServiceCode in (" + selectedServices + ") and SUBSTRING(DateTime,1,10) BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' \n" +
" GROUP BY Number\n" +
" HAVING SUM(Point) >= " + pointCount + ";\n";
}
drawQuery += " with DrawInfo (Number,RepCount) as \n" +
"( select Number,1 \n" +
" from temp.dbo." + tempTableName + "\n" +
" union all \n" +
" select DrawInfo.Number,DrawInfo.RepCount + 1 \n" +
" from Temp.dbo." + tempTableName + "\n" +
" inner join DrawInfo on (DrawInfo.Number = Temp.dbo." + tempTableName + ".Number and DrawInfo.RepCount + 1 <= " + tempTableName + ".RepCount) \n" +
")\n" +
" Insert into Temp.dbo." + finalTempTableName + "(Number) \n" +
" select DrawInfo.Number \n" +
" from DrawInfo";
if (!checkBoxOrderInformation.Checked)
drawQuery += " ORDER BY ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) \n";
else
drawQuery += " ORDER BY Number \n";
drawQuery += " option (maxrecursion 0);\n " +
" select count(*) from Temp.dbo." + finalTempTableName;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VasunReportConnectionString"].ConnectionString))
{
var command = new SqlCommand(drawQuery, connection) { CommandTimeout = 999999999 };
connection.Open();
drawFieldSet.Visible = true;
rowCount = (int)command.ExecuteScalar();
txtNumberOfRow.Text = rowCount.ToString(CultureInfo.InvariantCulture);
}
using (var dbs = new ReceiveSendEntitiesV5())
{
var matchDrawHistories = new MatchDrawHistory()
{
DrawStartDate = dtpStartDate.Text,
DrawEndDate = dtpEndDate.Text,
DrawTime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
RowNumber = rowCount,
ServiceCode = cblServices.SelectedValue,
TableName = finalTempTableName
};
dbs.MatchDrawHistories.Add(matchDrawHistories);
dbs.SaveChanges();
}
}
catch (Exception exp)
{
ErrorLabel.Text = "Exception :" + exp.Message;
}
}
but when there were a lot of data, my code execute until : txtNumberOfRow.Text = rowCount.ToString(CultureInfo.InvariantCulture);
so these codes does not execute :
using (var dbs = new ReceiveSendEntitiesV5())
{
var matchDrawHistories = new MatchDrawHistory()
{
DrawStartDate = dtpStartDate.Text,
DrawEndDate = dtpEndDate.Text,
DrawTime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
RowNumber = rowCount,
ServiceCode = cblServices.SelectedValue,
TableName = finalTempTableName
};
dbs.MatchDrawHistories.Add(matchDrawHistories);
dbs.SaveChanges();
}
how it is possible!!! what is the problem???
I am newbie to c# I want to have headers and footers when saving the text file which is generated on the data grid view.
when I run a sql query it should generate 3 column values as headers and 3 columns values as footers.
headers recordtype,cpcnumber,filesequence number;
footers record type,no of requests,total court fee,claim amount; I don't how to get these records when i run this command as headers/footers. Any help would be greatly appreciated..
private void btnGetData_Click(object sender, EventArgs e)
{
this.btnGetData.Enabled = false;
Application.DoEvents();
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([CPC No] +' ',30) " +
" , space(1983) " +
",'" + comboBox6.Text + " 'as RecordType" +
, left(t.t_reference + ' ' ,24 ) as ClaimantReference " +
" , left([Claim Number] +' ',30) " +
" , " + comboBox4.Text + " as CourtCode" +
" ,left(ta_title +' ',30) as Title " +
" ,left(ta_surname +' ',30) as Surname " +
", space(180), bat.PCN_Charge as ClaimAmount " +
",[Court Fee] " +
",[Solictors Fees]" +
", (bat.PCN_Charge + [Court Fee]) as TotalAmount" +
",[POC1]" +
",'" + textBox2.Text + "' as RequestType" +
//",'" + comboBox1.Text + "' as RecordType" +
",'" + textBox3.Text + "' as TotalCourtFee" +
",'" + textBox4.Text + "' as TotalClaimAmount" +
" , space(1966) " +
" FROM tickets t " +
" LEFT OUTER JOIN " +
"( " +
" SELECT ticket_addresses.ta_system_ref, ta_title, ta_othername, ta_surname, ta_house_number, ta_address_1, ta_address_2, " +
" ta_address_3, ta_address_4, ta_post_code, ta_telephone, ta_organisation " +
" FROM ticket_addresses " +
" INNER JOIN " +
" ( " +
" SELECT ticket_addresses.ta_system_ref, MAX(ta_address_code) AS ta_address_code " +
" FROM ticket_addresses " +
" GROUP BY ta_system_ref " +
" ) ad " +
" ON (ticket_addresses.ta_system_ref=ad.ta_system_ref AND ticket_addresses.ta_address_code=ad.ta_address_code) " +
")ta " +
"ON (t.t_number=ta.ta_system_ref) " +
" " +
" Inner JOIN " +
" ticket_hold_record b " +
" ON ( t.t_number = b.thr_system_ref) " +
" " +
"Inner JOIN " +
"Rpt_PCNBalance_ALLTickets bat " +
"ON (t.t_number = bat.t_number) " +
" " +
"Inner JOIN " +
"hold_reasons ch " +
"ON (b.thr_hold_type = ch.hr_code) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[Courtfees] cf " +
" ON (bat.Payments >= cf. [Min ClaimAmount]) and (bat.Payments <= cf.[Max Claim Amount]) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[sites] s " +
" ON (t.t_contract = s.Contract) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[claim info] cc " +
" ON (cc.Code COLLATE DATABASE_DEFAULT = t.t_offence_code COLLATE DATABASE_DEFAULT) " +
" and t.t_reference IN {where} ";
//Generate list of Ticket IDS for SQL Where Clause
string whereClause = "";
string[] tempArray = new string[this.txt.Lines.Length];
tempArray = this.txt.Lines;
if (this.txt.Lines.Length == 0)
{
return;
}
for (int counter = 0; counter <= tempArray.Length-1; counter++)
{
if (tempArray[counter].Trim().Length > 0)
{
whereClause = whereClause + "'" + tempArray[counter] + "'" + ", ";
}
}
whereClause = whereClause.TrimEnd(' ', ',');
whereClause = "(" + whereClause + ")";
stringSql = stringSql.Replace("{where}", whereClause);
myDataset = new DataSet("SQL");
SqlConnection myConn = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = stringSql;
myCommand.Connection = myConn;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myDataset);
this.dataGridView1.DataSource = myDataset.Tables[0];
for (int counter = 0; counter < myDataset.Tables[0].Columns.Count; counter++)
{
this.dataGridView1.Columns[counter].SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.Refresh();
myConn.Close(); this.btnGetData.Enabled = true;
this.btnSave.Enabled = true;
Application.DoEvents();
}