Linq IEnumerable to entity cast error - vb.net

Please refer to my following code. An exception error occurs at the return value.
Unable to cast object of type 'System.Data.Objects.ObjectQuery1[VB$AnonymousType_23[System.String,System.String,System.String]]' to type 'System.Collections.Generic.List`1[MyEntities.stk_cust]'.
Public Function GetCustomerProdListToGrid() As List(Of stk_cust)
Dim result = From s In Db.stk_cust
Group Join d In Db.s_armaster On d.dbcode Equals s.dbcode Into stk_ar = Group
From d In stk_ar.DefaultIfEmpty()
Order By s.stk_code, s.dbcode Ascending
Select s.stk_code, s.dbcode, d.name
Return result
End Function
I've tried the following method at select section but error turns out the same
Select New With {.stk_code = s.stk_code,
.dbcode = s.dbcode,
.name = d.name
}
Any help is highly appreciated.

If you want to return a List(Of stk_cust) you need to create instances of stk_cust instead of using an anonymous type. Presuming that those are the properties:
....
Select New stk_cust() With {
.stk_code = s.stk_code,
.dbcode = s.dbcode,
.name = d.name
}
Return result.ToList()
Maybe you could also select the object directly without needing to create a new one:
Dim result = From s In Db.stk_cust
Group Join d In Db.s_armaster On d.dbcode Equals s.dbcode Into stk_ar = Group
From d In stk_ar.DefaultIfEmpty()
Order By s.stk_code, s.dbcode Ascending
Select s
Return result.ToList()

Related

LINQ - No data to copy to datatable error

I encountered an error whenever there's no data to copy to datatable. I'm not able to assign the copied datatable to my variable.
My code ResultDT as Datatable format:
ResultDT = (From d In MainDT.AsEnumerable
Group d By k=d("UPDATED_BRN").ToString.Trim Into grp=Group
Let check = grp.Any(Function ( r ) CheckOrderDT.AsEnumerable.Any(Function (x) x("ACCNT_ID").ToString.Trim.Equals(r("ROW_ID").ToString.Trim )))
From g In grp
Let ra = New Object(){g(0),g(1),g(2),g(3),g(4),g(5),g(6),g(7),g(8),g(9), If(check, "Available",g(10))}
Select ResultDT.Rows.Add(ra)).CopyToDataTable
So I try to change it to check first before copy to datatable but I got a different error.
I change it to - FilteredRows as System.Collections.Generic.IEnumerable<System.Data.DataRow>:
FilteredRows = (From d In MainDT.AsEnumerable
Group d By k=d("UPDATED_BRN").ToString.Trim Into grp=Group
Let check = grp.Any(Function ( r ) CheckOrderDT.AsEnumerable.Any(Function (x) x("ACCNT_ID").ToString.Trim.Equals(r("ROW_ID").ToString.Trim )))
From g In grp
Let ra = New Object(){g(0),g(1),g(2),g(3),g(4),g(5),g(6),g(7),g(8),g(9), If(check, "Available",g(10))}
Select ResultDT.Rows.Add(ra))
ResultDT = If(FilteredRows.Any, FilteredRows.CopyToDatatable, MainDT.Clone)
But still encountered an error - Cannot assign to ResultDT.
Can anyone suggest a better idea to cater if there's not data in the datatable?

Entity framework vb.net error in translating query

I am trying to convert this query:
select sales.TTL_Sales_Net, sales.TTL_Sales_Target, units.TTL_Units_Net
from epos_Anal_Branch_Sales_Day sales
join epos_PULL_PM_SKU_STATUS till on sales.BRANCH_ID = till.BRANCH_ID
join epos_Anal_Branch_Units_Day units on sales.BRANCH_ID = units.BRANCH_ID
where till.BRANCH_ID = 45 and sales.DATEKEY = 20140725 and units.DATEKEY = 20140725
from SQL into an Entity Framework query in VB.net. I am sending in the BRANCH_ID in my function and producing the datekey like so:
Dim MyDate As String = Date.Now.ToString("yyyyMMdd")
This is what I have but it just returns no results and I am at a complete loss as to why! This is my query thus far, if anyone can spot what I have done wrong then I would be grateful for a push in the right direction
Public Class clsStoreSales
Public Property DailyAmount As String
Public Property DailyUnits As String
Public Property SalesTarget As String
Public Property ErrorMessages As String
Public Shared Function GetStoreSales(ByVal BranchID As String) As List(Of clsStoreSales)
Dim live As New RMISEntitiesLive
Dim MyDate As String = Date.Now.ToString("yyyyMMdd")
Dim l As New List(Of clsStoreSales)
Try
Dim r = From till In live.epos_PULL_PM_SKU_STATUS
Join sales In live.epos_Anal_Branch_Sales_Day On till.BRANCH_ID Equals sales.BRANCH_ID
Join units In live.epos_Anal_Branch_Units_Day On till.BRANCH_ID Equals units.DATEKEY
Where till.BRANCH_ID = CDbl(BranchID) AndAlso sales.DATEKEY = CDbl(MyDate) AndAlso units.DATEKEY = CDbl(MyDate)
Select New With {.SalesAmount = sales.TTL_Sales_Net, .SalesTarget = sales.TTL_Sales_Target, .SaleUnits = units.TTL_Units_Net}
For Each t In r
Dim m As New clsStoreSales
m.DailyAmount = CStr(t.SalesAmount)
m.DailyUnits = CStr(t.SaleUnits)
m.SalesTarget = CStr(t.SalesTarget)
l.Add(m)
Next
Return l
Catch ex As Exception
Dim e As New clsStoreSales
e.ErrorMessages = ex.ToString
l.Add(e)
Return l
End Try
End Function
End Class
This is what sqlServer Profiler is showing as the query being run:
exec sp_executesql N'SELECT
[Extent1].[BRANCH_ID] AS [BRANCH_ID],
[Extent2].[TTL_Sales_Net] AS [TTL_Sales_Net],
[Extent2].[TTL_Sales_Target] AS [TTL_Sales_Target],
[Extent3].[TTL_Units_Net] AS [TTL_Units_Net]
FROM [dbo].[epos_PULL_PM_SKU_STATUS] AS [Extent1]
INNER JOIN [dbo].[epos_Anal_Branch_Sales_Day] AS [Extent2] ON [Extent1].[BRANCH_ID] = [Extent2].[BRANCH_ID]
INNER JOIN [dbo].[epos_Anal_Branch_Units_Day] AS [Extent3] ON [Extent1].[BRANCH_ID] = [Extent3].[DATEKEY]
WHERE ( CAST( [Extent1].[BRANCH_ID] AS float) = #p__linq__0) AND ( CAST( [Extent2].[DATEKEY] AS float) = #p__linq__1) AND ( CAST( [Extent3].[DATEKEY] AS float) = #p__linq__2)',N'#p__linq__0 float,#p__linq__1 float,#p__linq__2 float',#p__linq__0=45,#p__linq__1=20140725,#p__linq__2=20140725
This
Join units In live.epos_Anal_Branch_Units_Day On till.BRANCH_ID Equals units.DATEKEY
Should be this!
Join units In live.epos_Anal_Branch_Units_Day On till.BRANCH_ID Equals units.BRANCH_ID

Linq To SQL: left join and vb.NET

I have this SQL query:
SELECT TOP 1 r.* FROM dbo.Request r
LEFT JOIN dbo.Process p
ON r.IdReq = p.IdReq
WHERE IdProcess Is NULL
ORDER BY r.ReqDate ASC
I want write it in a vb.net procedure, using Linq To SQL syntax:
Private Function getOldestRequest() As Request
Dim dc As ProcessDataContext = new ProcessDataContext(ConfigurationManager.ConnectionStrings("...").ConnectionString);
Dim pr = From r In dc.Request
From p In dc.Process.Where(Function(v) v.IdReq = r.IdReq And v.idProcess Is Nothing)
Select New {Request = r}
Return pr
End Function
This is what I wrote, but I get error, on the Return line.
LINQ statements return IEnumerable objects, and your method is returning a single Request object. In your case looks like you only need to return the first result of the LINQ statement.
Something like:
Dim pr = (From r In dc.Request
From p In dc.Process.Where(Function(v) v.IdReq = r.IdReq And v.idProcess Is Nothing)
Select New {Request = r}).FirstOfDefault
Return pr
Change your Select to
Select r
And your return to
Return pr.OrderBy(Function(v) v.RecDate).FirstOrDefault

Linq query returning value from another class

Just a quick question about LINQ, I want to use a value from the returned dataset to lookup a value and return this. The line I am struggling with is .ViewingNotes = New Viewing(pt.ProspectId).GetViewings().Columns(7).ToString(). Is this possible?
With BusinessLayerObjectManager.Context
Return (From p As [Property] In .PropertySet
Join pt As Prospect In .Prospects On pt.Property.propertyID Equals p.propertyID
Where (p.Development.DevelopmentID = devId)
Select New DevelopmentList With {
.Apartment = p.propertyApartment + " " + p.Development.Name,
.PropertyId = p.propertyID,
.Client = pt.Client.clientFirstname + " " + pt.Client.clientLastname,
.ClientId = pt.Client.ClientID,
.ProspectiveDate = pt.prospectiveDate,
.ProspectiveStatus = pt.prospectiveStatus,
.Agent = pt.Client.userID,
.ViewingNotes = New Viewing(pt.ProspectId).GetViewings().Columns(7).ToString(),
.PropertyStatus = ""
}).ToList()
End With
Thanks in advance.
I suspect not, when the compiler tries to convert the 'Viewing(pt.ProspectId).GetViewings().Columns(7).ToString()' bit to SQL it will get very confused. You would need to do it in 2 stages.
Do the first Linq-to-entity select first returning just pt.ProspectId, with the .ToList() intact. Then use the results to do some more linq, linq-to-linq if you like, where you can do the lookup using a lambda.

Convert an object System.Data.Linq.DataQuery to System.Linq.IQueryable?

How can I convert an object of type System.Data.Linq.DataQuery to System.Linq.IQueryable?
I'm working with Visual Basic/Silverlight, and the source code of my query is as follows:
Public Function Get_Cli_Pag() As IQueryable(Of V_Cliente_Pagare)
Dim Qry = From P In Me.Context.Pagares Join C In Me.Context.Codigos On C.Codigo
Equals P.Tipo_Pagare Where P.Nulo = 0 And P.Extraviado = 0 And C.Clave = 5 Select P.Rut, P.Cliente.Nombre, P.Tipo_Pagare, Tipo_Pagare_Descripcion = C.Descripcion, P.Pagare
Return Qry.AsQueryable
End Function
Does the .AsQueryable extension method work?