I have a the following setup
m_handsets = From p In RL.App.TComEntities.tblTelephoneNumbers _
Where p.companyId = m_CompanyID _
Select p
m_handsets = DirectCast(m_handsets, ObjectQuery(Of RL.TelephoneNumbers)).Include("tblCalls")
where m_handsets is defined as
Private m_handsets As IQueryable(Of RL.tblTelephoneNumbers)
which works as expected however what I want to do know is query the Navigation property (tblCalls) so I can do something like the following
From p In m_handsets.tblCalls
Where m_handsets.tblCalls.price > 100
but I have no idea of the proper syntax, can anyone help?
EDIT:
I think the complexity comes here because in this instance I could have 5 tblTelephoneNumbers in m_handsets and then x amount of calls for that particular telephone number. I am interested in the tblCalls for each but I would like to filter them all for each tblTelehoneNumber.
Entity Diagram which (hopefully) should illustrate further
So I currently know all the handsets that are associated with the company I am interested in. I can also see the calls loaded as a navigation property in debug mode, but I want to say is take this filter (in this example price>100 and apply it to all handsets->calls
If understand your question correctly, then you have 2 solutions to accomplish this:
In both solution you'll see that I remove the Include method since Include does NOT allow you to filter the related data.
1. Filtered Projection (Returns Anonaymous Type):
Dim results = From p In RL.App.TComEntities.tblTelephoneNumbers _
Where p.companyId = m_CompanyID _
Select New With {.Handsets = p, _
.tblCalls = p.tblCalls.Where(Function(t) t.price > 100)}
However, it might not be desirable in all situations as it gives a collection of anonymous type objects.
2. Two Tracked Queries (Returns EntityObjects):
This one gives you a collection of your entityobject tblTelephoneNumbers:
Dim m_handsets = (From p In RL.App.TComEntities.tblTelephoneNumbers _
Where p.companyId = m_CompanyID Select p).ToList()
Dim m_tblCalls = (From t In RL.App.TComEntities.tblCalls _
Where t.price > 100 Select t).ToList();
ForEach(Dim t In m_tblCalls)
m_handsets.Single(Function(h) h.ID = t.tblTelephoneNumberID).tblCalls.Add(t)
End ForEach
3. Leveraging Attach Method (Returns EntityObjects):
The last and probably the best and most elegant solution is to use EntityCollection.Attach Method along with EntityCollection.CreateSourceQuery:
foreach (var tel in m_handsets) {
IQueryable<tblCalls> sourceQuery = tel.tblCalls.CreateSourceQuery()
.Where(c => c.price > 100);
tel.tblCalls.Attach(sourceQuery);
}
Sorry for any VB syntax mistake, I wrote them all off the top of my head.
Related
So I have an Entity Framework 5 model that includes a many-to-many relationship.
CategoryValues --< CourseCategoryValues >-- Courses
I have a LINQ query that selects every Course in the database. I would really like to modify it to only select Courses that belong to a specific CategoryValue. My attempt thus far has failed?
Can anyone help me figure this out?
This is what I have tried:
Using database As SiteDataContext = New SiteDataContext
database.Configuration.ProxyCreationEnabled = False
database.Courses.Include("Classes")
database.Courses.Include("CourseCategoryValues")
query = (From c In database.Courses Select c Order By c.Name).Where(
Function(c) 0 < c.Classes.Where(Function([class]) [class].Status.ToLower = "open").Count
).Include(Function(r) r.Classes).Include(Function(r) r.CourseCategoryValues)
' Here is where I am trying to narrow down the query results
If (pid.HasValue) AndAlso (0 <> pid.Value) Then
query.Where(Function(c) c.CourseCategoryValues.Any(Function(v) v.CategoryValue.CategoryValueID = pid))
End If
model.PageData = query.ToList
End Using
I think you are only missing the assignment of the filter to the query variable. Where returns a new queryable, it doesn't modify the queryable you apply the Where to. So, you would need:
query = query.Where(...)
The Where expression itself looks correct to me.
I have a query in the DB:
SELECT GreenInventoryBlendGradeID,bgx.blendgradeid,
bgX.GreenBlendGradeTypeID,[Description]
FROM [GreenInventory] gi
INNER JOIN [GreenInventoryBlendGradeXref] bgX
ON bgX.[GreenInventoryID] = gi.[GreenInventoryID]
INNER JOIN [BlendGrade] bg
ON bg.[BlendGradeID]=bgx.[BlendGradeID]
That returns 3 records:
TypeID Desc
1 XR
2 XR
1 XF2
The LINQ:
var GreenInventory = (from g in Session.GreenInventory
.Include("GreenInventoryBlendGradeXref")
.Include("GreenInventoryBlendGradeXref.BlendGrade")
.Include("GreenInventoryBlendGradeXref.GreenBlendGradeType")
.Include("GreenInventoryWeightXref")
.Where(x => x.GreenInventoryID == id && x.GreenInventoryBlendGradeXref.Any(bg=>bg.GreenBlendGradeTypeID > 0) )
select g);
I have tried different Where clauses including the simple - (x => x.GreenInventoryID == id)
but always have only the first 2 records returned.
Any Ideas?
If I try the following:
var GreenInventory = (from gi in Session.GreenInventory.Where(y => y.GreenInventoryID == id)
join bgX in Session.GreenInventoryBlendGradeXref.DefaultIfEmpty() on gi.GreenInventoryID equals bgX.GreenInventoryID
join bg in Session.BlendGrade.DefaultIfEmpty() on bgX.BlendGradeID equals g.BlendGradeID
select new { GreenInventory = gi, GreenInventoryBlendGradeXref = bgX, BlendGrade = bg });
I Get back 3 of each objects and the correct information is in the BlendGrade objects. It looks like the 3 GreenInventory objects are the same. They each include 2 of the GreenInventoryBlendGradeXref objects which show the the same 2 records as before.
So I not clear on what the original problem was. Also dont know if this is the best way to resolve it.
Thanks for the answers. If anyone has a further thoughts please let us know.
Based on the few details you present, I would assume that you are missing a join. I have no experience with EntityFramework (I assume that you use this ORM), but as far as I know, the ".Include" tries to ensure that the set of root entities will not change and will not contain duplicates.
Your manually created query seems to indicate that there is at least one 1:n relationship in the model. The result you get from LINQ show that only distinct GreenInventory entities are returned.
Therefore you need to adjust your query and explicitly declare that you want all results (and not only distinct root entities) - I would assume that with an explicit join EntityFramework will yield all expected results - or you need to adjust your mapping.
The first place I'd look in would be your model and joins you have defined between the entities. You might also want to check your generated SQL statement:
Trace.WriteLine(GreenInventory.Provider.ToString())
or use Visual Studio IntelliTrace to investigate what was sent to the database.
I have the following LINQ query that selects all the pages that have a menu associated with them. I now want to pull out all the pages that don’t have a menu associated with them I.e.. all the pages in Pages that don’t exist in “AssociatedPages”.
var AssociatedPages = (from mm in db.MainMenus
join p in db.Pages on mm.MainMenuPageFK equals p.PageID
select p);
var unAssociatedPages = (from p in db.Pages
where ???
select p);
return View(unAssociatedPages);
I’ve done this before in SQL but I’m not sure on the LINQ syntax.
The setup is one MainMenu can have one too many Pages associated with it
Any help would be greatly appreciated.
Try this:
var unAssociatedPages =
from p in db.Pages
join mm in db.MainMenus on p.PageID equals mm.MainMenuPageFK into mms
where !mms.Any()
select p;
You may find that you need to pop in a couple of .ToArray() calls to improve performance.
I've got a problem with Linq in VB.NET.
I've created a .dbml file from my db, and everything looks good - relation "arrows" between tables are visible, etc.
But when I want to use simple query (taken from 101 Linq Samples by MS):
Dim q = From h In dc.Hours, w In h.WorkType
I receive an error:
Expression of type 'INTegrity.WorkType' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
h.Worktype is visible in Intellisense...
I can manually join in the Linq query, but shouldn't the relations be automatic?
The full query that works, but using "manual joins" looks like this:
Dim q1 = From g In dc1.Hours _
Join pr In dc1.WorkType On g.WorkTypeId Equals pr.WorkTypeId _
Where g.WorkerId = workerid _
Select New With {g.EntryId, g.Date, pr.WorkTypeDesc, g.Minutes}
Worktype table has 1 to many relationship with Hours table (as you can see on the WorkTypeId column)
I don't speak LINQ in VB, so I'll try to adapt to C#
From h In dc.Hours, w In h.WorkType
from h in dc.Hours
from w in h.WorkType
.....
This implies that WorkType is a collection, which it's name does not suggest. I think you want something closer to
from h in dc.Hours
let w = h.WorkType
....
Of course, none of these will do anything without the parts in the "....". If you show us what you want to do there, we could probably fix it for you.
UPDATE#1:
Trying to piece together what you are doing, let's guess that Hours & WorkType are tables with a one-to-many relationship (WorkType on the "one" side), hence every Hours record matchs one WorkType record. In that case, Linq-to-SQL will automatically generate a scalar WorkType property in Hours. You don't need the "from ... in " to access it. It's just a property, use it directly where you need it.
UPDATE#2: (From comments)
I think this should work:
Dim q1 =
From g In dc1.Hours
Where g.WorkerId = workerid
Select New With {g.EntryId, g.Date, g.WorkType.WorkTypeDesc, g.Minutes}
I'm getting an Entity Framework object collection from my Products table called oProducts. I am looping through the collection and setting the Quantity field from a separate function. Before I write out a display of the objects in HTML, I want to sort them by the Quantity. So, I am using LINQ to create a new collection and try to order from the object collection that I just modified. The modified values are definitely in the object collection and output properly, but the sort ordering isn't working on the modified field. Does anyone know what I'm overlooking or a better way to attempt this?
Dim oProducts = From p in ctx.Products _
Where p.Active = True _
Select p
For Each prod in oProducts
prod.Quantity = GetQuantity(prod.ProductID)
Next
Dim oOrderedProducts = From p in oProducts _
Order By p.Quantity Ascending _
Select p
For Each prod in oOrderedProducts
Response.Write(prod.Quantity.ToString())
'*** The Quantities are stored in the collection properly but it doesn't order by the Quantity field.
Next
There a few things you need to remember:
Doing From p in ctx.Products _ will always select from the database.
LINQ is lazy. It will not perform the database select until you iterate, and if you iterate twice, it will do the database select twice.
How data read from the database is combined with data already in the ObjectContext will vary based on the MergeOption of the query you execute. But it will always happen after the SQL is executed.
With those ideas in mind, let's consider your code:
This bit (1) creates an IQueryable<Product> which can be used as a basis for iteration or defining other queries. Note that it does not actually execute a database query.
Dim oProducts = From p in ctx.Products _ // (1)
Where p.Active = True _
Select p
The next bit (2) iterates the IQueryable defined above.
For Each prod in oProducts // (2)
prod.Quantity = GetQuantity(prod.ProductID)
Next
Doing so causes a selection from the database. Inside the loop, you mutate the object that's returned. In LINQ to Objects, this would have no effect whatsoever, because the next time you iterated the IQueryable it would be executed anew. However, Entity objects are special. Mutating them marks the entity is changed on the context. Calling SaveChanges() later would save those modifications to the database.
It's important to note, however, that you have not changed the IQueryable variable oProducts at all by doing this. It is still a reference to a query which will be executed every time it is iterated. It is not a list. If you want a list, you need to call ToList() or ToArray().
The following query (3) creates a new IQueryable based on the original oProducts. When iterated, this will produce new SQL which does much the same as the original query, except for the ordering you've added. Again, oProducts is a query, not a list.
Dim oOrderedProducts = From p in oProducts _ // 3
Order By p.Quantity Ascending _
Select p
Finally, your code executes a new database query based on the IQueryable you defined above. As it executes this query, it merges the information retrieved from the database with the knowledge about the mutation you did above from the object context. Because the ordering is based on the query you defined, it is performed on the database server, using information in the database. Because information from the database is merged with information from the object context, you still see the mutation you performed on the data above, in (2).
For Each prod in oOrderedProducts
Response.Write(prod.Quantity.ToString())
'*** The Quantities are stored in the collection properly but it doesn't order by the Quantity field.
Next
You don't need to use the 3 consecutive LINQ expressions, combine them into one, using projection, either into an anonymous type (as I did here) or a real one.
This, below, should work
var oProducts = From p in ctx.Products
Where p.Active == True
orderby p.Quantity Ascending
select new
{
Quantity = GetQuantity(p.ProductID)
// ... assign other properties too
}
foreach ( var prod in oProducts )
{
// do your output
}
How about this?
Dim oProducts = From p in ctx.Products _
Where p.Active = True _
Select p
For Each prod in oProducts
prod.Quantity = GetQuantity(prod.ProductID)
Next
Dim oOrderedProducts = oProducts.OrderBy(Function(p) p.Quantity)