ASP.net LINQ on DataView to use Like query - linq

I want to filter a DataView but DV.Rowfilter is taking too much time .
dv.RowFilter = "ProductName like '%" + searchtxt + "%'";
So I decided to use the LINQ but how to implement above like query in LINQ ?

LINQ is not more efficient in general, but it can increase readability and maintainability.
So you can try Linq-To-DataSet:
var query = from row in dv.Table.AsEnumerable()
let productName = row.Field<string>("ProductName")
where productName.Contains(searchtxt)
select row;
DataTable tbl = query.CopyToDataTable(); // use this as DataSource or use tbl.DefaultView
Here the same with method syntax:
var query = dv.Table.AsEnumerable()
.Where(row => row.Field<string>("ProductName").Contains(searchtxt));
MSDN: Creating a DataView Object with LINQ to DataSet
i have tried your second solution, but now its throwing the exception
"The source contains no DataRows." and actually the DataTable which i
make as DataTable.AsEnumerable() , it has the rows in it
The table contains rows but the filter skips all of them.
You could use if(query.Any()){...} to check if there are rows:
DataTable tbl = dv.Table.Clone(); // creates an empty table with the same columns
if(query.Any())
tbl = query.CopyToDataTable();

Related

How to query dataset table on primary key of smallInt using linq C#

Let say I have the following sql table. Customer_id column is a primary key with smallint.
And I am trying to create a linq query, where I want to get all data for customer with id, let say 1.
How to do this.
Already done and not working:
1.
var query = from row in dt.AsEnumerable()
where row.Field<Int32>("customer_id") == Convert.ToInt32(2)
select row;
2.
var query = from row in dt.AsEnumerable()
where row.Field<Int16>("customer_id") == Convert.ToInt16(2)
select row
debug for example 1,2
Syntax error
Exceptions
Why don't you use this:
DataRow needle = hayStack.Tables["Customer"].Rows.Find(2);
Your method should be rewritten as something like this:
private DataRow GetCustomerDetails(Int16 customer_id)
{
return _dt.Tables["Customer"].Rows.Find(customer_id);
}
The calling method would have to check for null beeing returned from the method, since an invalid customer_id would cause Find() tu return null.
Try using short type instead of Int32.

How to replicate in LINQ a SQL query that uses Coalesce to pivot rows into a single column

How can I achieve this functionality from SQL in LINQ?
Here I am getting 3 SP Number to one Contract ID:
DECLARE #Names VARCHAR(8000)
SELECT #Names = COALESCE( #Names + ', ', '') + us.SP_NBR
FROM CAATS_ADMIN.CONTRACT_SP us
WHERE US.CNTRCT_ID='1000038'
You can use the LINQ aggregate function. You will need to retrieve the data in a SELECT to a list of strings through whatever data access mechanism you are using then you use the Aggregate like this:
List<string> source = GetMyData();
var b = source.Aggregate ("",
(current, s)=> string.Concat(current, string.Format("{0},", s)) );
This applies the string concatenation to every item in the sequence to build a single string.

How this linq execute?

Data = _db.ALLOCATION_D.OrderBy(a => a.ALLO_ID)
.Skip(10)
.Take(10)
.ToList();
Let say I have 100000 rows in ALLOCATION_D table. I want to select first 10 row. Now I want to know how the above statement executes. I don't know but I think it executes in the following way...
first it select the 100000 rows
then ordered by ALLO_ID
then Skip 10
finally select the 10 rows.
Is it right? I want to know more details.
This Linq produce a SQL query via Entity Framework. Then it depends on your DBMS, but for SQL Server 2008, here is the query produces:
SELECT TOP (10) [Extent1].[ALLO_ID] AS [ALLO_ID],
FROM (
SELECT [Extent1].[ALLO_ID] AS [ALLO_ID]
, row_number() OVER (ORDER BY [Extent1].[ALLO_ID] ASC) AS [row_number]
FROM [dbo].[ALLOCATION_D] AS [Extent1]
) AS [Extent1]
WHERE [Extent1].[row_number] > 10
ORDER BY [Extent1].[ALLO_ID] ASC
You can run this in your C# for retrieve the query:
var linqQuery = _db.ALLOCATION_D
.OrderBy(a => a.ALLO_ID)
.Skip(10)
.Take(10);
var sqlQuery = ((System.Data.Objects.ObjectQuery)linqQuery).ToTraceString();
Data = linqQuery.ToList();
Second option with Linq To SQL
var linqQuery = _db.ALLOCATION_D
.OrderBy(a => a.ALLO_ID)
.Skip(10)
.Take(10);
var sqlQuery = _db.GetCommand(linqQuery).CommandText;
Data = linqQuery.ToList();
References:
How do I view the SQL generated by the entity framework?
How to: Display Generated SQL
How to view LINQ Generated SQL statements?
Your statement reads as follows:
Select all rows (overwritten by skip/take)
Order by Allo_ID
Order by Allo_ID again
Skip first 10 rows
Take next 10 rows
If you want it to select the first ten rows, you simply do this:
Data = _db.ALLOCATION_D // You don't need to order twice
.OrderBy(a => a.ALLO_ID)
.Take(10)
.ToList()
Up to the ToList call, the calls only generates expressions. That means that the OrderBy, Skip and Take calls are bundled up as an expression that is then sent to the entity framework to be executed in the database.
Entity framework will make an SQL query from that expression, which returns the ten rows from the table, which the ToList methods reads and places in a List<T> where T is the type of the items in the ALLOCATION_D collection.

LINQ self join in ASP.NET MVC3

I have a situation where I need to do a self join on a table in LINQ. The table consists of fields ItemsID, Title, SeriesTitle, and many other. An item can be either a series or members and I can tell that by looking into ItemId which has "S" or "M" letters on it. I need to retrieve all records that are member of a series with ItemId "S117". I can do this in simple SQL by the code below,
select i.Series_Title, i.Item_ID, i2.Item_ID as Member_ID,
i2.Title as Member_Title, i2.Series_Title as Member_Series_Title
from Items i join Items i2 on i.Series_Title = i2.Series_Title
where i.Item_ID = "S117"
Now, I translated this query in LINQ which goes as
items = _dataContext.Items.AsQueryable();
items = from series in items
join members in items on series.Series_Title.ToLower()
equals members.Series_Title.ToLower()
where series.Item_ID.ToLower().Equals(itemId)
select series;
The last line of this query select series will only retrieve series but not members and I need members also.
I am using MVC3 Razor view where I have to display almost all fields so I am not using select new {....}
Even when I tried to use select new {series, members}, I got this exception -
Cannot implicitly convert type
'System.Linq.IQueryable'
to 'System.LinQ.IQueryable<My.App.models.Items>'
An explicit conversion exist.
Any suggestions would be highly appreciated.
Try this:
var items1 = _dataContext.Items.AsQueryable();
var items2 = from series in items1
join members in items1 on series.Series_Title
equals members.Series_Title
where series.Item_ID== 'S117'
select series;

Adding a random Guid column to a Linq to Entities query to grab random records

I've found some articles about using the RandomView view and the GetNewID function to pull back randomized records, but they are using this method with Linq to SQL which allows Functions and Stored Procs to be used with no return value or a scalar return value. From what I understand, a Stored Proc has to been returned as one of the Entity Framework objects from my generated model. I have been able to get that to work as an object, but not returning a scalar or no return set.
What I want to do is to simply add a column to my Linq query that contains a newly generated Guid so that I can order by the new Guids and take a specific number of records randomly. Can anyone help with some sort of lambda expression or join that would enable me to do this? It seems like it should be something built into EF, but I understand that we are on EF v1.
(Please provide code in VB.net)
In the Select clause of your Linq query, you should be able to insert a GUID like this:
var result = from myRecord in myTable
select new {
field1 = myRecord.field1,
field2 = myRecord.field2,
guidField = Guid.NewGuid()
};
Well, my VB is a little rusty, but I think this will work...
Dim result =
From myRecord in myTable _
Select field1, _
field2, _
guidField = System.Guid.NewGuid()

Resources