So out of the blue, an application (WPF, MVVM) is throwing an exception when performing a linq query. This query is performed in two different views but is character-for-character exactly the same. Only one view throws and exception.
LINQ to Entities does not recognize the method 'System.Data.Entity.DbSet`1[DQSA.Entities.DrugScan] SetDrugScan' method, and this method cannot be translated into a store expression.
The query is as follows:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Linq.Dynamic;
using System.Linq.Expressions;
//....
var contents = (from i in ctx.Set<Entities.ToteContents>()
where i.ToteID == ToteID
group i by i.Drug into g
select new
{
Drug = g.Key,
QtyShipped = g.Sum(x => x.Qty),
QtyScanned = (ctx.Set<Entities.DrugScan>()
.Where(x => x.ToteID == ToteID && x.DrugID == g.Key.DrugID)
.Count())
}).ToList();
The working view renders a PDF report using this data with no problem. It's in the same project as the non-working view and the #includes are the same as well. So I am at a loss to explain the issue.``
Related
PVS Studio throws V3137: The 'funclist' variable is assigned but is not used until the end of the function. Program.cs 13
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace V3137_False_Positive
{
class Program
{
static void Main()
{
List<(string name, Func<Task> func)> funclist;
funclist = new List<(string name, Func<Task> func)>
{
("Test", new Func<Task>(() => Task.CompletedTask)),
};
foreach ((string name, Func<Task> func) in funclist)
{
var task = func;
}
}
}
}
Is this a false positive?
Looks like a false positive. We'll try fixing it in one of the future releases.
Also, false-positive reports are not the entirely right format of questions for stackoverflow, so consider sending them directly to PVS-Studio support at support#viva64.com or https://www.viva64.com/en/about-feedback/.
Thanks for your feedback!
Basically,
I would like to convert odata query expression "$filter", "itemID eq 1" to where(w=>w.itemID==1)
Is there a ready library for this operation? Otherwise I need to code it by using DynamicLinq classes and linqKit.
I'm using Microsoft WebAPI with the following NuGet packages installed:
http://nuget.org/packages/Microsoft.Data.OData/
http://nuget.org/packages/microsoft.aspnet.webapi.odata
Which lets me write things like:
using System.Web.Http;
using System.Web.Http.OData.Query;
// Some stuff left out
[Queryable]
public IQueryable<Item> Get(ODataQueryOptions<Item> query)
{
var items = query.ApplyTo(from item in context.Items select item);
return (IQueryable<Item>) items;
}
Then I can call it using jQuery Ajax (for the sake of the example, I prefer to use BackboneJS) like this:
$.ajax({ url: '/api/items', data: $.param({ '$filter': 'ID eq 1' }) });
Which will then return only the items with an ID equal to 1, which I think is what you are after?
If itemID is the main ID of the object you are retrieving, I would probably follow REST principles and create and API where the url to retrieve an item with the ID of 1 would be:
/api/items/1
And only use oData queries on the collection of items if I was querying based on other properties of the items in the collection, or do something like below for example when retrieving the top 10 records.
$.ajax({ url: '/api/items', data: $.param({ '$top': 10 }) });
You can use following NuGet package to apply filter:
https://www.nuget.org/packages/Community.OData.Linq
Code sample would be:
using System.Linq;
using Community.OData.Linq;
// dataSet in this example - any IQuerable<T>
Sample[] filterResult = dataSet.OData().Filter("Id eq 2 or Name eq 'name3'").ToArray();
Currently supported: filter and orderby in v4 format
You Can use Microsoft.Rest.Azure.OData
string filter = new ODataQuery(x => x.itemID == 1).Filter;
I am writing an application on windows to get the information of Motherboard. The information I want to collect is
Motherboard Manufacturer (e.g. Dell or Gigabyte)
Motherboard Model (e.g. T3600 or GA-Z77)
Can anyone please tell me which API I should use to get this information?
this is the first answer as a thank u for this site
frist add a System.Management refrence to your project
and try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// First we create the ManagementObjectSearcher that
// will hold the query used.
// The class Win32_BaseBoard (you can say table)
// contains the Motherboard information.
// We are querying about the properties (columns)
// Product and SerialNumber.
// You can replace these properties by
// an asterisk (*) to get all properties (columns).
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT Product, SerialNumber FROM Win32_BaseBoard");
// Executing the query...
// Because the machine has a single Motherborad,
// then a single object (row) returned.
ManagementObjectCollection information = searcher.Get();
foreach (ManagementObject obj in information)
{
// Retrieving the properties (columns)
// Writing column name then its value
foreach (PropertyData data in obj.Properties)
Console.WriteLine("{0} = {1}", data.Name, data.Value);
Console.WriteLine();
}
// For typical use of disposable objects
// enclose it in a using statement instead.
searcher.Dispose();
Console.Read();
}
}
}
hope that will help
[Using LLBLGen Pro 3.1 with Entity Framework 4, .NET 4 and SQLServer 2005]
I've got a linq query that includes .Contain(keyword);
IEnumerable<Product> products = null;
using (var context = new ModelDataContext())
{
products = (from product in context.Products where product.Title.Contains(keyword)
select product);
}
I was looking into the performance of the query and discovered that when the SQL is generated it's actually a "like '%keyword%'" that is being generated not a contains.
After doing a bit of research I came across some info in the LLBLGen Pro documentation regarding FunctionMapping:
http://www.llblgen.com/documentation/2.6/Using%20the%20generated%20code/Linq/gencode_linq_functionmappings.htm
I've created a table-valued function on my sql database, and also the classes required within my project:
public class CustomDatabaseFunctions
{
public static bool FullTextSearch(string fieldToSearch, string toFind)
{
// empty body, as it's just here to make the query compile. The call is converted to a SQL function.
return true;
}
}
public class CustomDatabaseFunctionMappings : FunctionMappingStore
{
public CustomDatabaseFunctionMappings() : base()
{
this.Add(new FunctionMapping(typeof(CustomDatabaseFunctions),"FullTextSearch",1,"Product_FullTextSearch({0})","ProductDatabase","Resources"));
}
}
The next part of the documentation states that you need to pass the custom FunctionMappingStore to the LinqMetaData. In the example this is done as follows:
metaData.CustomFunctionMappings = new NorthwindFunctionMappings();
var q = from o in metaData.Order where o.CustomerId == "CHOPS"
select new { o.OrderId, OrderTotal = NorthwindFunctions.CalculateOrderTotal(o.OrderId, true) };
The problem I have is that I'm doing my linq query using the DataContext and I've no idea where the variable metaData comes from or how to use it!
I'll keep looking to see if I can find out but any help very welcome!
the documentation you're linking to is for our framework, yet you're saying you're using EFv4. So you should use the function mapping feature of EF, not our own framework ;). That is, if you're using EF, but the code suggests you don't. So I'm very confused.
It's also better to post questions about LLBLGen Pro on our own support forums as we don't monitor SO.
How would the following sql query look when translated to linq?
SELECT
myId, Count(myId)
FROM MyTable
GROUP BY myId
I've tried the following:
var q = from a in db.MyTable
group a by a.Id into g
let count = g.Count()
select new
{
Count = Id,
Key= g.Key
};
but it raises an exception on enumeration indicating that there is no db function with a mapping named 'Key'. I'm using LLBLGen on this particular app and I suspect that's where the problem is rooted. I want to verify that my linq syntax is correct before I start digging though. Anyone see anything wrong?
Try this:
var q = from a in db.MyTable
group a by a.Id into g
select new { Id=g.Key, Count=g.Count() };
That's nearly the same as yours, but your Count is obtained in a different way which looks wrong to me.
If LLBLGen doesn't understand IGrouping.Key though, it could be tricky...
To check whether your LINQ syntax is correct or not, I'd recommend building a very simple in-memory list to use as your table. Here's an example:
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main()
{
var data = new[] {
new { Id="X", Name="Jon" },
new { Id="Y", Name="Marc" },
new { Id="X", Name="Holly" },
};
var query = from a in data
group a by a.Id into g
select new { Id=g.Key, Count=g.Count() };
foreach (var entry in query)
{
Console.WriteLine(entry);
}
}
}
This looks like it's giving the right results to me.