how to copy data to data table in linq step by step process in linq - asp.net

I am fresher in linq,So please give me the link or write step by step procedure to fill data table in linq.
here is the code
var Sql = from t1 in pitbull.ACC_APP1_QuickViews.AsEnumerable()
join t2 in pitbull.OCC_VehicleGroups.AsEnumerable()
on t1.VehicleId equals t2.VehicleID
select new
{
t1.Lat,
t1.Lon,
t1.Timestamp_GPS,
t1.Speed,
t1.Location,
t1.Status,
t1.VehicleRegNo,
t1.VehicleId,
t2.VGID,
t2.VGName
};
DataTable dt = new DataTable();enter code here
dt=Sql.copytodatatable();
//copy to datatable not support.Improve question Permalink

It is because you are creating a anonymous type using select new{ } to hold the Field objects. Try this:
var Sql = from t1 in pitbull.ACC_APP1_QuickViews.AsEnumerable()
join t2 in pitbull.OCC_VehicleGroups.AsEnumerable()
on t1.VehicleId equals t2.VehicleID
select t2;
DataTable dt = Sql.copytodatatable();

Related

how to avoid duplicate values in db context object in asp.net core

ALTER PROC [dbo].[rendertutorials](#courname nvarchar(30))
AS
BEGIN
SELECT
tu.FkCategoryid AS Fcatid
,tu.Title
,tu.content
,tu.Keywords
,tu.Metadata
,tu.tags
,cat.CategoryName
,cat.CourseName
,cat.courseimagepath AS imgpath
FROM GetCategories AS cat
INNER JOIN GetTutorials AS tu ON cat.CategoryId = tu.FkCategoryId
WHERE tu.publish = 1 AND cat.coursename LIKE '%' + #courname + '%'
END
GO
EXEC[rendertutorials] "mvc"
AS you can see the store procedure will produce the correct data. item[0] ... item[n] are different.
public IActionResult Tutorials()
{
//var data = GetTableLastChanges("listoftitiles #title", 1, "#title");
var data = db.getrenderview.FromSqlRaw("rendertutorials #courname={0}", "mvc").ToList();
return View(data);
}
But when I call the stored procedure from code the above data variable contain the same data (from item[0] till item[n]). Why? What did I miss?
use distinct in sql:
SELECT DISTINCT column1, column2, ...
FROM table_name;

ASP.NET RDLC: Display field from another table in tablix

I have a ASP.NET MVC 4 project with EF. I have a ASPX Web Page to display a ReportControl for RDLC reports.
There I have 2 tables : Orders and Agents. In my report I want to display (in a Tablix) all my orders.
OrderNo | OrderDate | OrderTotal | OrderStatus | Agent
(Agent column is the name of the agent : "Agent.Name")
Q : How can I display a field(Agent.Name) from another table(Agent) in a Tablix?
if (!IsPostBack)
{
var qry = FROM o in db.Orders
//JOIN a in d.Agents on o.idAgent equals a.idAgent
SELECT o; //
ReportDataSource dataSource = new ReportDataSource("DataSetOrder_Agent", qry);
ReportViewerOrders.LocalReport.DataSources.Add(dataSource);
}
Using SP:
CREATE PROCEDURE [dbo].spAgentOrders
(
#fromdate DATE,
#todate DATE
)
AS
DECLARE #from DATE = #fromdate, #to DATE = #todate
SELECT o.orderbo, o.orderdate, o.ordervalue, o.status, a.name
FROM orders o
JOIN agent a on o.id_agent = a.id_agent
WHERE o.orderdate between #from and #to
RETURN
Update the Model, add the SP as a Function Import that returns a complex type.
2. Webform codebehind:
if (!IsPostBack)
{
//...
var qry = db.spAgentOrders(tbFrom.Text, tbTo.Text);
ReportDataSource dataSource = new ReportDataSource("DataSetOrder_Agent", qry);
ReportViewerOrders.LocalReport.DataSources.Add(dataSource);
}
Update the report's DataSource .xsd. Drag the SP from Server Explorer.

Massive Query with inner join not returning any data

I'm using the Massive Query method to write a simple join query against an Oracle database. This is my code with the query simplified even further by taking out some columns:
dynamic logTable = new DynamicModel("mydatabase", "table1");
var sb = new StringBuilder();
sb.Append("select CONTACT_ID from table1 inner join table2 on table1.ID = table2.ID ");
sb.Append("where table1.ID=:0");
dynamic dbResult = logTable.Query(sb.ToString(), id);
The following code gives me an error: 'object' does not contain a definition for 'CONTACT_ID'
string id = dbResult.CONTACT_ID.ToString();
If I take the exact query and run it through sqldeveloper, I get back the expected results. If I try to Query through Massive without a join, I get back an object I can work with.
Any ideas?
My mistake! I was expecting my query to return only one record, but forgot that Query returns IEnumerable. Solution is to take First() or loop over the results.

perform "not in" query using linq from 2 datatables

i have a datatable which contains "InvalidCodes".
Before uploading the data to database(data is still in datatable), i want to perform linq on the datatable to remove Invalid entries and move them in another datatable
datatable allEntries ( entries yet to be uploaded in database)
datatable InvalidCodes(single column datatable - retrieved from database)
datatable invalidEntries
right now "allEnties" contains valid entries and invalid entries. the linq query on "allEntries" should move the nonexistend code entries to invalidEntries datatable.
plz help me perform this.
below is the query i formed but its not valid
string query = "select [CityCode] from [StateCity] ";
DataTable citylist = getDataTableFromSelect(query);
var result = from myrow in inputDt.AsEnumerable()
where !myrow.Field<string>("CityCode").Contains(from myrow2 in citylist.AsEnumerable() select myrow2.Field<string>("CityCode") )
select myrow;
I'd make a HashSet for the invalid city codes - this will allow the code to quickly/efficiently identify which of the codes are in the invalid set.
e.g. something like:
var invalidCityCodes = from myrow2 in citylist.AsEnumerable()
select myrow2.Field<string>("CityCode");
var invalidCityCodeHashSet = new HashSet<string>(invalideCityCodes);
var result = from myrow in inputDt.AsEnumerable()
where !invalidCityCodeHashSet.Contains(myrow.Field<string>("CityCode"))
select myrow;
You can also take both the results in 2 Different Lists and then you can
use
List1 = List1.RemoveAll(Item=>List2.Contains(Item))
This works fine with me and will work for you also.

DataGrid view in asp.net is not displaying data

I want to dispaly column in datagrid view using custom query statement
but i want to send value to parametrized data in query
how can i do this ?
my code is below
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'cus0010' and a.account_number = 'acc0010'
this above code working properly in sql server 2005
but the code below which is modified as per asp.net page for grid view is not showing
any result
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'Label1.Text' and a.account_number = 'Label2.Text'
the above is placed in my custom sql query section it
is triggered by button click in my asp page or any other
idea to display it will be welcomed
Use:
string.Format("c.customer_id = '{0}' and a.account_number = '{1}'", Label1.Text, Label2.Text);
Consider this query:
string query = "insert into TestTable (Column1, Column2) values (#p1, #p2)";
p1 & p2 are parameters, in order to set the value for the parameters you need to use:
queryParameters[0] = new SqlCeParameter("p1", SqlDbType.NVarChar);
queryParameters[0].Value = Label1.Text;
queryParameters[1] = new SqlCeParameter("p2", SqlDbType.NVarChar);
queryParameters[1].Value = Label2.Text;
SqlCeCommand command = new SqlCeCommand(query);
command.Parameters.AddRange(queryParameters);
When the wizard is generating the query you need to use place holders/parameters for customer_ID and account_number and set their values by using parameters.
Edit:
In order to make the wizard create a parameter to use in the query, add a ? in the filter column in the query builder wizard.
Well, I may misunderstand, but...you are not actually sending the string 'Label1.Text' I guess? You should send the value of the textbox, something like this (if you are building the SQL as a string?):
...[SQL]... + "c.customer_id = '"+ Label1.Text + "'" ...[rest of the SQL]

Resources