I am using Rob's implementation of LazyList and it is working great.
However, I am not able to get a .where clause working on a child entity of the type LazyList.
For eg. something like
var qry = orderRepository.GetOrders();
qry = from p in qry where p.Items.Where(t => t.Name == "test") select p;
produces the following compile time error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Items>' to 'bool'
What is the correct way to query a child entity?
You need Any.
var qry = orderRepository.GetOrders();
qry = from p in qry where p.Items.Any(t => t.Name == "test") select p;
You already have a where clause, and using a second one won't do any good. The first where (the lowercase one) wants a boolean to be able to perform the filtering, but you are providing an IEnumerable<Items> (because that is what the second .Where returns). Any works the same as Where but returns a boolean whenever there's at least one item that matches the query you specified.
Not sure what you are trying to achieve with this statement.
If you want all the orders that have an item with the name "test" then use:
var qry = orderRepository.GetOrders();
qry = from p in qry where p.Items.Any(t => t.Name == "test") select p;
If you want all items that are named "test" then use:
var qry = orderRepository.GetOrders();
qry = from p in qry select p.Items.Where(t => t.Name == "test");
Related
I am calling the following function from a web service but can't get the object defined.
Dim x = (From a In _db.report _
Select ep = a.CurrentReport, CuCy = a.Current_Cycle) _
.Union _
(From b In _db.Counts _
Group b By b.Year, b.Report Into k() _ <--------(this is undefined)
Select ep = b.Report, CucY = b.Year).ToList().Take(10)
Is this the correct way to do a group by in a union query?
I would appreciate any help.
The Grouping syntax in VB is slightly different than C#. The Group By requires you to state Into Group rather than aliasing the new structure. See if the following works for you:
Dim x = (From a In _db.report _
Select ep = a.CurrentReport, CuCy = a.Current_Cycle) _
.Union _
(From b In _db.Counts _
Group By b.Year, b.Report Into Group _ <--------(this is undefined)
Select ep = Key.Report, Key.Year).ToList().Take(10)
Since you don't appear to be aggregating in the second query, you might be able to just do a distinct instead:
From b in _db.Counts
Select b.Report, B.Year
Distinct
Is there a way I can rewrite the following query to make it just one query?
try
{
var fileIds = (from f in context.SignalTo
where f.SignalFileID == 2
select new { f.GFileID }).ToList();
foreach (var id in fileIds)
{
var pp = (from p in context.ProjectFiles
where p.FileID == id.GFileID && p.ProjectID == ProjectID
select p);
if (pp != null)
{
ProjectFiles projectFile =(ProjectFiles) pp;
projectFile.MStatus = Status;
projectFile.DateLastUpdated = DateTime.Now;
context.SaveChanges();
}
}
}
You can combine the two query parts of your code into one.
You would then need to loop over the result set, making your updates. You would then call context.SaveChanges to submit all changes in one batch.
I can't tell if your existing code actually runs or compiles, but you need something like this:
Get the list of file ids you're interested in:
var fileIds = from f in context.SignalTo
where f.SignalFileID == 2
select f.GFileID;
fileIds is at this point an IQueryable where I assume T is an Int. No query has been excuted yet.
Now you can do
var pps = from p in context.ProjectFiles
where fileIds.Contains(p.FileID) && p.ProjectID == ProjectID
select p;
Still no query executed.
Then iterate over the result set
foreach( var pp in pps ) // query executed now
{
pp.MStatus = Status;
pp.DateLastUpdated = DateTime.Now;
}
context.SaveChanges(); // batch of updates executed now
Hello I need to join two tables (MainTransaction and Subtransaction), the problem here is I also want to get all the record of Maintransaction that's not in the Subtransaction, I am stuck in this part, how can I achieve this ?
protected object SelectMainTbl()
{
var mainIdAndSum = from st in t.subtransaction
group st by st.MainTransactionId into g
select new
{
Sum = (from r in g
select r.Amount).Sum(),
MainId = g.Key
};
var mainTbl = from main in t.maintransaction
join sub in mainIdAndSum on main.MainTransactionId equals sub.MainId
where main.IsEnabled == true && (sub.Sum - main.Amount != 0)
select main;
return mainTbl;
}
I think this is the query that you want:
from mt in t.maintransaction
join st in t.subtransaction
on mt.MainTransactionId equals st.MainTransactionId
into sts
where mt.IsEnabled
where sts.Sum(x => x.Amount) - mt.Amount != 0
select new
{
MainTransaction = mt,
Subtransactions = sts,
};
I want to generate dynamic query to check manage the where clause with number of parameters available...if some parameter is null i don't want to include it in the where clause
var test = from p in _db.test
where if(str1 != null){p.test == str} else i dnt wanna check p.test
I have around 14 parameters for the where clause
need help,
thanks
You can do it in steps:
// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
test = test.Where(p => p.test == str);
}
In addition to #Fredrik's answer, you can also use the short-circuit rules when evaluating boolean expressions like so:
var test = from p in _db.test
where str1 == null || p.test == str1;
Edit If you have lots of strings to test, (str1, str2, etc...) then you can use the following, which will be translated to an SQL IN clause:
var strings = new List<string>();
if (str1 != null) strings.Add(str1);
if (str2 != null) strings.Add(str2);
if (str3 != null) strings.Add(str3);
...
var test = from p in _db.test
where strings.Contains(p.test);
It's even easier if your strings are already in a collection (which, if you've got 14 of them, I assume they would be...)
Consider param1 and param2 are the parameters. Your query should be as under:
string param1 = "Value1";
string param2 = "Value2";
var q = from bal in context.FxBalanceDetails
where (string.IsNullOrEmpty(param1) || bal.Column1 == param1)
&& (string.IsNullOrEmpty(param2) || bal.Column2 == param2)
select bal;
This will ensure that the where clause gets applied for the particular parameter only when it is not null.
var test =
from p in _db.test
where p.str1 != null ? p.str1 : ""
select p;
Do you check the strings against the same Field of the entity?
If so you can write something like:
var strings = new[] { "foo", "bar", "ok", "", null };
var query = dataContext.YourTable.AsQueryable();
query = strings.Where(s => !string.IsNullOrEmpty(s))
.ToList()
.Aggregate(query, (q, s) => q.Where(e => e.YourField == s));
EDIT:
The previous solution is overcomplicated:
var strings = new[] { "foo", "bar", "ok", "", null }.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var query = dataContext.YourTable.Where(e => strings.Contains(e.YourField));
I've got a query in C# that is working for me to query the metadata for the Entity Framework. I need to convert it to VB.NET, but I'm struggling to convert the AS keyword to "cast" meta to System.Data.Metadata.Edm.EntityType. I've tried TryCast, CType, Cast, etc.
Here's the query in C#:
var queryResult = from meta in oc.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == System.Data.Metadata.Edm.BuiltInTypeKind.EntityType)
from p in (meta as System.Data.Metadata.Edm.EntityType).Properties
.Where(p => p.DeclaringType.Name == entityClassType.Name
&& p.Name == propertyName)
select p;
This is the closest I've come to getting it to compile in VB.NET (the As keyword in underlined and says ')' expected:
Dim query2 = _
From meta In entityObjectContext.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace) _
.Where(Function(m) m.BuiltInTypeKind = System.Data.Metadata.Edm.BuiltInTypeKind.EntityType) _
From p In (meta As System.Data.Metadata.Edm.EntityType).Properties _
.Where(Function(p) p.DeclaringType.Name = entity.GetType().Name _
And p.Name = propertyName) _
Select p
This is killing me. I'm so close...
You can use CType to type cast:
...
From p In CType(meta, System.Data.Metadata.Edm.EntityType).Properties _
...
Update: Looking again at the query, I would suggest using OfType() instead:
From meta In entityObjectContext.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace) _
.OfType(Of System.Data.Metadata.Edm.EntityType)() _
From p In meta.Properties _
Where p.DeclaringType.Name = entity.GetType().Name _
And p.Name = propertyName _
Select p
Update 2: Also, it looks like GetItems() has a generic version that I suspect will return only items of your desired type:
From meta In entityObjectContext.MetadataWorkspace.GetItems(Of System.Data.Metadata.Edm.EntityType)(System.Data.Metadata.Edm.DataSpace.CSpace) _
From p In meta.Properties _
Where p.DeclaringType.Name = entity.GetType().Name _
And p.Name = propertyName _
Select p
If I were writing this query in VB.NET, I would do it like this without the lambdas. I think it's easier to read, but they way you're doing it would probably be easier for a C# developer to read.
Dim query2 = _
From meta In entityObjectContext.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace) _
Where m.BuiltInTypeKind = System.Data.Metadata.Edm.BuiltInTypeKind.EntityType _
From p In CType(meta, System.Data.Metadata.Edm.EntityType).Properties _
Where p.DeclaringType.Name = entity.GetType().Name _
And p.Name = propertyName) _
Select p