Creating LINQ to SQL for counting a parameter - linq-to-sql

I'm trying to translate a sql query into LINQ to SQL. I keep getting an error "sequence operators not supported for type 'system.string'" If I take out the distinct count part, it works. Is it not because I'm using the GROUP BY?
SELECT COUNT(EpaValue) AS [Leak Count], Location, EpaValue AS [Leak Desc.]
FROM ChartMes.dbo.RecourceActualEPA_Report
WHERE (EpaName = N'LEAK1') AND (Timestamp) > '20100429030000'
GROUP BY EpaValue, Location
ORDER BY Location, [Leak Count] DESC
Dim temp = (From p In db2.RecourceActualEPA_Reports _
Where (p.Timestamp >= str1stShiftStart) And (p.Timestamp < str2ndShiftCutoff) _
And (p.EpaName = "Leak1") _
Select p.EpaName.Distinct.Count(), p.Location, p.EpaValue)

p.EpaName seems to be a string, not a collection so you can't apply Count() there.
Here is the query you're trying to build (according to your SQL query) using LINQ (I'm not familiar with VB, so the query is written in C#):
var temp =
db2.RecourceActualEPA_Reports
.Where(p =>
p.Timestamp >= str1stShiftStart &&
p.Timestamp < str2ndShiftCutoff &&
p.EpaName == "Leak1"
).GroupBy(p => new { Key1 = p.EpaValue, Key2 = p.Location })
.Select(g => new
{
Count = g.Count(),
Value = g.Key.Key1,
Location = g.Key.Key2
}).OrderBy(i => new { i.Location, i.Count });
And please, in the future format and highlight your code using this, not (or not only) using VS/Management Studio.

Here is how it is formatted in SQL and in Visual Studio
SQL
SELECT COUNT(EpaValue) AS [Leak Count], Location, EpaValue AS [Leak Desc.]
FROM ChartMes.dbo.RecourceActualEPA_Report
WHERE (EpaName = N'LEAK1') AND (Timestamp) > '20100429030000'
GROUP BY EpaValue, Location
ORDER BY Location, [Leak Count] DESC
VB
Dim temp = (From p In db2.RecourceActualEPA_Reports _
Where (p.Timestamp >= str1stShiftStart) And (p.Timestamp < str2ndShiftCutoff) _
And (p.EpaName = "Leak1") _
Select p.EpaName.Distinct.Count(), p.Location, p.EpaValue)

Related

Linq to Sql - Count, sub-query and subtraction

I am trying to convert the following T-SQL statement into Linq to Sql but am having trouble with the subtraction from the count. The final select will be a single row and single column (int)
I have done the SQL in two ways (sub-query and by JOIN/GROUP) which both return the same result, although I think the former might be the 'easier' option...
SQL 1 using a sub-query...
SELECT e.Places - ( SELECT COUNT(*) FROM [Event Participants] ep WHERE ep.E__ID = x AND ep.EP_STAT IN ('B','C')) AS AvailablePlaces
From Events e
WHERE e.E__ID = x
SQL 2 using GROUP BY and JOIN...
SELECT e.Places - COUNT(ep.E__ID) AS AvailablePlaces
FROM Events e
JOIN [Event Participants] ep ON e.E__ID = ep.E__ID
WHERE e.E__ID = x AND ep.EP_STAT IN ('B','C')
GROUP BY e.Places
Something like
var array = new string[] { "B", "C" };
var result = (from e in Event where e.E__ID == x
let count = (from ep in Event_Participants
where ep.E__ID == e.E__ID &&
array.Contains(ep.EP_Stat)
select ep).Count()
select e.Places - count
)
.Single();
Depending on your model, it might be possible to use navigation properties in the subquery.

Convert sql query with a join on a subselect to a linq statement

I am trying to convert the following sql query to LINQ statement
SELECT t.*
FROM (
SELECT Unique_Id, MAX(Version) mversion
FROM test
GROUP BY Unique_Id
) m INNER JOIN
test t ON m.Unique_Id = t.Unique_Id AND m.mversion = t.Version
LINQ statement
var testalt = (from altt in CS.test
group altt by altt.Unique_Id into g
join bp in CS.alerts on g.FirstOrDefault().Unique_Id equals bp.Unique_Id
select new ABCBE
{
ABCName= bp.Name,
number = bp.Number,
Unique_Id = g.Key,
Version = g.Max(x=>x.Version)
});
I am getting an error of where clause. Please help
SQL FIDDLE
This is not an easy straight forward conversion but you can accomplish the same thing using linq method syntax. The first query is executed to an expression tree, then you are joining that expression tree from the grouping against CS.alerts. This combines the expression tree from CS.test query into the expression tree of CS.alerts to join the two expression trees.
The expression tree is evaluated to build the query and execute said query upon enumeration. Enumeration in this case is the ToList() call but anything that gets a result from the enumeration will execute the query.
var query1 = CS.test.GroupBy(x => x.Unique_Id);
var joinResult = CS.alerts.Join(query1,
alert => new { ID = alert.Unique_Id, Version = alert.Version },
test => new { ID = test.Key, Version = test.Max(y => y.Version },
(alert, test) => new ABCBE {
ABCName = alert.Name,
number = alert.Number,
Unique_Id = test.Key,
Version = test.Max(y => y.Version)
}).ToList();
Because query1 is still an IQueryable and you are using CS.alerts (which I'm guessing CS is your data context) it should join and build the query to execute upon the ToList() enumeration.

How to write a Linq query equivalent to this SQL

I'm trying to figure out how to write a linq query that will return equivalent results to the sql query below. The problem I'm having has to do with the two select count queries included in the select list of the main query. I need to get counts of two different types of records from the PaymentHistory table for the last year. Can the equivalent of this be written using linq? Preferrably using lambda syntax.
select ieinum, serviceaddrkey,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 100) as ReturnedFees,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 101) as CorrectedReturnedFees
from Serviceaddr
Any help will be great.
Perhaps something like this:
from s in Serviceaddr
let ph = PaymentHistory.Where(p => s.serviceaddrkey == p.serviceaddrkey &&
p.PostDate >= DateTime.Now.AddYears(-1))
select new
{
s.ieinum,
s.serviceaddrkey,
ReturnedFees = ph.Count(p => p.SetID == 100),
CorrectedReturnedFees = ph.Count(p => p.SetID == 101)
}

LINQ Generating Bad Query, Error Unknown Column (VB.NET MySQL)

I'm developing in MVC2 using VB.NET and MySQL and ran into a problem trying to convert a simple SQL query to LINQ.
SQL Query:
SELECT Location_Number, sum(Column1) as totalC1, sum(Column2) as totalC2
FROM MyTable
WHERE year = 2010 and month = 8
GROUP BY Location_Number
ORDER BY Location_Number
LINQ Query:
From r In MyTable _
Where r.Year = 2010 And r.Month = 8 _
Group r By LN = r.Location_Number Into l = Group _
Order By LN _
Select New With { _
.Location_Number = LN, _
.DepositCount = l.Sum(Function(r) r.Column1), _
.OtherCount = l.Sum(Function(r) r.Column2) _
}
The error generated is:
An error occurred while executing the command definition. See the inner exception for details.
The inner exception is:
Unknown column 'GroupBy1.K1' in 'field list'
Here is the SQL generated by LINQ:
SELECT `Project1`.`Location_Number`, `Project1`.`C1`, `Project1`.`C2`
FROM (
SELECT `GroupBy1`.`A1` AS `C1`, `GroupBy1`.`A2` AS `C2`, `GroupBy1`.`K1` AS `Location_Number`
FROM (
SELECT Sum(`Column1`) AS `A1`, Sum(`Column2`) AS `A2`
FROM `MyTable` AS `Extent1`
WHERE (`Extent1`.`Year` = #p__linq__0) AND (`Extent1`.`Month` = #p__linq__1)
GROUP BY `Extent1`.`Location_Number`
) AS `GroupBy1`
) AS `Project1`
ORDER BY `Location_Number` ASC
Looking at that query its easy to spot whats causing the error. Simply, the most inner query only returns 2 columns, while the query right above it is trying to SELECT 3, thus the Unknown Column Error. So why is this happening? What is wrong with my LINQ query?
Thank you
It is a MySQL connector bug: http://bugs.mysql.com/bug.php?id=46742
Is not fixed in last (6.3.5) version.
Good news! That bug was fixed on 6.3.7 (see comments in http://bugs.mysql.com/bug.php?id=46742).
Yes, it's a mySQL connector bug.
Try this:
Using context = New YourContext()
Dim sql = "SELECT Location_Number, sum(Column1) as totalC1, sum(Column2) as totalC2 FROM MyTable WHERE year = #YEAR and month = #MONTH GROUP BY Location_Number ORDER BY Location_Number"
Dim args = New DbParameter()
{
New SqlParameter() With {Key .ParameterName = "YEAR", Key .Value = 2010}, New SqlParameter() With {Key .ParameterName = "MONTH", Key .Value = 8}
}
Return context.ExecuteStoreQuery(Of MyTable)(sql, args).ToList()
End Using

Why would AccessDataSource return different results to query in Access?

I have a query to return random distinct rows from an Access database. Here is the query:
SELECT * FROM
(SELECT DISTINCT m.MemberID, m.Title, m.FullName, m.Address,
m.Phone, m.EmailAddress, m.WebsiteAddress FROM Members AS m INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY RND(members.MemberID) DESC
When I run this in Access it returns the rows in different order every time, as per the random sort order. When I run it through my web app however the rows return in the same order every time. Here is how I call it in my code-behind:
private void BindData()
{
using (AccessDataSource ds = new AccessDataSource("~/App_Data/mydb.mdb", GetSQLStatement()))
{
ds.DataSourceMode = SqlDataSourceMode.DataReader;
ds.CacheDuration = 0;
ds.CacheExpirationPolicy = DataSourceCacheExpiry.Absolute;
ds.EnableCaching = false;
listing.DataSource = ds.Select(new DataSourceSelectArguments());
listing.DataBind();
if (listing.Items.Count == 0)
noResults.Visible = true;
else
noResults.Visible = false;
}
}
I added in all that stuff about caching because I thought maybe the query was being cached but the result was the same. I put a breakpoint in the code to make sure the query was the same as above and it was.
Any ideas? This is driving me nuts.
When executing the ACE/Jet RND function against a new connection the same seed value is used each time. When using MS Access you are using the same connection each time, which explains why you get a different value each time.
Consider these VBA examples: the first uses a new connection on each iteration:
Sub TestDiff()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
Dim i As Long
For i = 0 To 2
.Open
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
.Close
Next
End With
End Sub
Output:
0.705547511577606
0.705547511577606
0.705547511577606
Note the same value each time.
The second example uses the same connection on each iteration (the .Open and .Close statements are relocated outside the loop):
Sub TestSame()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
.Open
Dim i As Long
For i = 0 To 2
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
Next
.Close
End With
End Sub
Output:
0.705547511577606
0.533424019813538
0.579518616199493
Note different values each time.
In VBA code you can use the Randomize keyword to seed the Rnd() function but I don't think this can be done in ACE/Jet. One workaround is to use the least significant decimal portion of the ACE/Jet the NOW() niladic function e.g. something like:
SELECT CDBL(NOW()) - ROUND(CDBL(NOW()), 4) FROM OneRowTable
I would move the RND into the inner SELECT
SELECT * FROM
(SELECT DISTINCT m.MemberID, RND(m.MemberID) as SortOrder, m.Title,
m.FullName, m.Address, m.Phone, m.EmailAddress, m.WebsiteAddress
FROM Members AS m
INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID
WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY
Members.SortOrder DESC
You can use time as one argument to the RND field
Dim Now As DateTime = DateTime.Now
Dim millSec As Integer = Now.Millisecond
finalQuery = "SELECT * FROM wordInfo ORDER BY Rnd(-(1000* ROUND(" + millSec.ToString("N") + ", 0)) * [ID])"
So here from date and time value, millisecond value is taken which will be integer and it is used in sql query by rounding it.
wordInfo is table name
ID is the column name in database table
This gives random order every time (since millisecond value is different) be it same connection or new connection.