linq-to-sql fails if local list variable - linq-to-sql

I'm struggling to get what I thought would be a simple LINQ-to-SQL query to work. I can construct the query ok and can verify that the SQL it generates is correct but when executing get the dreaded "System.NotSupportedException: Queries with local collections are not supported" exception.
I've simplified my query but in short the query below works:
var query = from asset in context where new[] { 1, 2, 3 }.Contains(asset.code) select asset
this query also works:
var query = from asset in context where new List<int>() { 1, 2, 3 }.Contains(asset.code) select asset
But the query below will fail when an attempt is made to get the result set:
List<int> myList = new List<int>(){1, 2, 3};
var query = from asset in context where myList.Contains(asset.code) select asset
Anyone solved this sort of issue?

What you posted should work, leading me to believe you didn't actually post the broken code.
Make sure that the MyList variable is a List<int> and not an IList<int>... if the variable type is IList<int>, you'd get that exception.

This works fine for me in LINQPad:
List<int> myList = new List<int>(){1, 2, 3}; /* Fixed your compiler error here */
var query = from asset in assets where myList.Contains(asset.code) select asset;
As such, I assume you aren't actually using a List for myList, but rather a generic IEnumerable or something similar?
Please try pasting your "unsimplified" version, as your simplication corrects your error.

Related

RDF4J SPARQL query to JSON

I am trying to move data from a SPARQL endpoint to a JSONObject. Using RDF4J.
RDF4J documentation does not address this directly (some info about using endpoints, less about converting to JSON, and nothing where these two cases meet up).
Sofar I have:
SPARQLRepository repo = new SPARQLRepository(<My Endpoint>);
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "SPARQL/JSON");
repo.setAdditionalHttpHeaders(headers);
try (RepositoryConnection conn = repo.getConnection())
{
String queryString = "SELECT * WHERE {GRAPH <urn:x-evn-master:mwadata> {?s ?p ?o}}";
GraphQuery query = conn.prepareGraphQuery(queryString);
debug("Mark 2");
try (GraphQueryResult result = query.evaluate())
this fails because "Server responded with an unsupported file format: application/sparql-results+json"
I figured a SPARQLGraphQuery should take the place of GraphQuery, but RepositoryConnection does not have a relevant prepare statement.
If I exchange
try (RepositoryConnection conn = repo.getConnection())
with
try (SPARQLConnection conn = (SPARQLConnection)repo.getConnection())
I run into the problem that SPARQLConnection does not generate a SPARQLGraphQuery. The closest I can get is:
SPARQLGraphQuery query = (SPARQLGraphQuery)conn.prepareQuery(QueryLanguage.SPARQL, queryString);
which gives a runtime error as these types cannot be cast to eachother.
I do not know how to proceed from here. Any help or advise much appreciated. Thank you
this fails because "Server responded with an unsupported file format: application/sparql-results+json"
In RDF4J, SPARQL SELECT queries are tuple queries, so named because each result is a set of bindings, which are tuples of the form (name, value). In contrast, CONSTRUCT (and DESCRIBE) queries are graph queries, so called because their result is a graph, that is, a collection of RDF statements.
Furthermore, setting additional headers for the response format as you have done here is not necessary (except in rare circumstances), the RDF4J client handles this for you automatically, based on the registered set of parsers.
So, in short, simplify your code as follows:
SPARQLRepository repo = new SPARQLRepository(<My Endpoint>);
try (RepositoryConnection conn = repo.getConnection()) {
String queryString = "SELECT * WHERE {GRAPH <urn:x-evn-master:mwadata> {?s ?p ?o}}";
TupleQuery query = conn.prepareTupleQuery(queryString);
debug("Mark 2");
try (TupleQueryResult result = query.evaluate()) {
...
}
}
If you want to write the result of the query in JSON format, you could use a TupleQueryResultHandler, for example the SPARQLResultsJSONWriter, as follows:
SPARQLRepository repo = new SPARQLRepository(<My Endpoint>);
try (RepositoryConnection conn = repo.getConnection()) {
String queryString = "SELECT * WHERE {GRAPH <urn:x-evn-master:mwadata> {?s ?p ?o}}";
TupleQuery query = conn.prepareTupleQuery(queryString);
query.evaluate(new SPARQLResultsJSONWriter(System.out));
}
This will write the result of the query (in this example to standard output) using the SPARQL Query Results JSON format. If you have a non-standard format in mind, you could of course also create your own TupleQueryResultHandler implementation.
For more details on the various ways in which you can process the result (including iterating, streaming, adding to a List, or just directly sending to a result handler), see the documentation on querying a repository. As an aside, the javadoc on the RDF4J APIs is pretty extensive too, so if your Java editing environment has support for displaying that, I'd advise you to make use of it.

Understanding cyclomatic complexity

I have some piece of code that basically looks like this:
public MyObject getData(boolean someFlag) {
String select1 = "SELECT * FROM myTable WHERE someInteger = ?";
SqlHostvariablen hostvars = new SqlHostvara();
hostvars.addInteger(myField.getSomeInteger);
String[][] selarray = SqlHelper.doSelectAsMatrix(select1, hostvars);
if (selarray.length == 0) {
throw new IllegalArgumentException("Nothing found");
}
MyObject foo = new MyObject();
int i = 0;
foo.setSomething1(selarray[0][i++]);
foo.setSomething2(selarray[0][i++]);
foo.setSomething3(selarray[0][i++]);
foo.setSomething4(selarray[0][i++]);
foo.setSomething5(selarray[0][i++]);
foo.setSomething6(selarray[0][i++]);
foo.setSomething7(selarray[0][i++]);
foo.setSomething8(transformSomething8(selarray[0][i++]));
foo.setSomething9(selarray[0][i++]);
foo.setSomething10(selarray[0][i++]);
String someValue1 = selarray[0][i++];
String someValue2 = selarray[0][i++];
foo.setSomething11(selarray[0][i++]);
doSomethingWithFoo(foo, someFlag, someValue1, someValue2);
doSomethingElseWithFoo(foo);
return foo;
}
The identifiers and SQL statement are anonymized but otherwise my method looks the same.
Now Checkstyle claims that the cyclomatic comlexity if this method is 12. I always thought I knew what CC was and from my knowledge I'd say this methods CC is 2. There is one if that creates a new path through the code and the control flow graph therefore has 2 paths/exit points. I don't see where else there should be a path through the code.
Am I missing something entirely or is Checkstyle just wrong?
Turned out this was a Checkstyle error. While not even cleaning the problem did the trick, after a system restart the warning was gone. An Eclipse restart might have been enough, no way to know for sure.

Entity Framework 4.0 Code-First Dynamic Query

I would like to query a table based on a list of KeyValuePair. With a Model-First approach, I could do the following:
var context = new DataContext();
var whereClause = new StringBuilder();
var objectParameters = new List<ObjectParameter>();
foreach(KeyValuePair<string, object> pair in queryParameters)
{
if (whereClause.Length > 0)
whereClause.Append(" AND ");
whereClause.Append(string.Format("it.[{0}] = #{0}", pair.Key));
parameters.Add(new ObjectParameter(pair.Key, pair.Value));
}
var result = context.Nodes.Where(whereClause.ToString(), parameters.ToArray());
Now I'm using a Code-First approach and this Where method is not available anymore. Fortunately, I saw an article somewhere (I can't remember anymore) which suggested that I could convert the DbContext to a IObjectContextAdapter then call CreateQuery like this:
var result = ((IObjectContextAdapter)context)
.ObjectContext.CreateQuery<Node>(whereClause.ToString(), parameters.ToArray());
Unfortunately, this throws an error:
'{ColumnName}' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly.
Where {ColumnName} is the column specified in the whereClause.
Any ideas how I can dynamically query a DbSet given a list of key/value pairs? All help will be greatly appreciated.
I think your very first problem is that in the first example you are using Where on the entity set but in the second example you are using CreateQuery so you must pass full ESQL query and not only where clause! Try something like:
...
.CreateQuery<Node>("SELECT VALUE it FROM ContextName.Nodes AS it WHERE " + yourWhere)
The most problematic is full entity set name in FROM part. I think it is defined as name of the context class and name of the DbSet exposed on the context. Another way to do it is creating ObjectSet:
...
.ObjectContext.CreateObjectSet<Node>().Where(yourWhere)

LinqtoSQL with a where clause containing a List?

I have researched this to death. There does seem to be some answers here already, but frankly the answers confuse me. So I'll try to make this as basic as possible.
If I have a table in a database, "People" with a name column(string) and an age(int) column. Then I do something like this:
List<int> ages = new List<int>();
ages.Add(39);
ages.Add(40);
var result = from p in People
where ages.Contains((int)p.Age)
select p;
The syntax is passing, but returns nothing (both in VS2010 and LinqPad). Shouldn't this make a SQL statement with a where clause containing the ages in my list?
Simple answer anyone? (Ideally if you could modify my example and make it work.. that would be great!)
if you are doing it as Linq2SQL, it appears you are doing it correctly in order to ensure the proper projections for SQL Server. You may try writing it a slightly different way, like:
var result = from p in People
where ages.Select(a => a).Contains(p.Age)
select p;
You say that it returns nothing. Are you sure that there are matching records to return? Also, are you using result anywhere? The query won't execute if you don't bind it to something or call ToList() to some other projecting interaction.
Sample from comments:
var ints = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var Merchandiser = (new DataClasses1DataContext()).Merchandisers;
var result = from m in Merchandiser
where ints.Contains(m.Id)
select m;
foreach (var item in result)
{
Console.WriteLine(item.Name);
}
Console.ReadLine();

Populate JOIN into a list in one database query

I am trying to get the records from the 'many' table of a one-to-many relationship and add them as a list to the relevant record from the 'one' table.
I am also trying to do this in a single database request.
Code derived from Linq to Sql - Populate JOIN result into a List almost achieves the intended result, but makes one database request per entry in the 'one' table which is unacceptable. That failing code is here:
var res = from variable in _dc.GetTable<VARIABLE>()
select new { x = variable, y = variable.VARIABLE_VALUEs };
However if I do a similar query but loop through all the results, then only a single database request is made. This code achieves all goals:
var res = from variable in _dc.GetTable<VARIABLE>()
select variable;
List<GDO.Variable> output = new List<GDO.Variable>();
foreach (var v2 in res)
{
List<GDO.VariableValue> values = new List<GDO.VariableValue>();
foreach (var vv in v2.VARIABLE_VALUEs)
{
values.Add(VariableValue.EntityToGDO(vv));
}
output.Add(EntityToGDO(v2));
output[output.Count - 1].VariableValues = values;
}
However the latter code is ugly as hell, and it really feels like something that should be do-able in a single linq query.
So, how can this be done in a single linq query that makes only a single database query?
In both cases the table is set to preload using the following code:
_dc = _db.CreateLinqDataContext();
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<VARIABLE>(v => v.VARIABLE_VALUEs);
_dc.LoadOptions = loadOptions;
I am using .NET 3.5, and the database back-end was generated using SqlMetal.
This link may help
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Look under join operators. You'll probably have to change from using extension syntax other syntax too. Like this,
var = from obj in dc.Table
from obj2 in dc.Table2
where condition
select