Could not find an implementation of the query 'Select' not found - c#

My error is:
Could not find an implementation of the query pattern for source type
'System.Data.Entity.Database'. 'Select' not found.
My relevent code is:
DatabaseEntities db = new DatabaseEntities();
var whichUi = from UiType in db.Database
select AdvancedUi;
I am using the linq import (common answer on other threads).

I think your error is that you try to select something from .Database directly, not from the table. Instead of this code:
from UiType in db.Database
try out something like this:
from UiType in db.UiTypes
select UiType.AdvancedUi;
This should work as the table UiTypes will implemet the IEnumerable interface.
You should put your table name after the in keyword.
UiType is just a placeholder, and can be anything you want. Please, pay attention to the select clause - you must use the placeholder there, not the table name.

In my case, I resolved the error by changing:
var results = db.MyStoredProc().Select(x => x);
Or,
var results = from x in db.MyStoredProc()
select x;
To,
var results = db.MyStoredProc();
HTH.

The whole logic behind the query syntax/fluent syntax is to select an object as a whole or to select a property of an object.
Look at this following query:
var result = (from s in _ctx.ScannedDatas.AsQueryable()
where s.Data == scanData
select s.Id).FirstOrDefault();
Please note that after the where clause I am selecting only the Id property of the ScannedData object.
So to answer your question, if AdvancedUi is a property of UiTypes class then your query should be more like:
var result = from UiType in db.UiTypes
select UiType.AdvancedUi;
Alternatively if you want to return all data from a table say ScannedDatas, then your query will be:
var listResult = (from d in _ctx.ScannedDatas
select d).ToList();
Hope this answers your question my friend.

Related

Dynamic Linq 'contains' clause without using placeholder

The syntax given for contains clause is
ids = new int[] {1,2,3,4};
dataContext.Table.Where("#0.Contains(id)", ids);
But what I want is
dataContext.Table.Where("{1,2,3,4}.Contains(id)"); //getting exception here
[ERROR] Expression expected (at index 0)
I need this because the where clause my or may not use the contains method. it depends on how user acts.
so I got the answer for this after tinkering for sometime. So posting the answer here.
dataContext.Table.Where("new Int[]{1,2,3,4}.Contains(id)");
You can use whatever datatype you need. I use reflection to find datatype and use that accordingly.
try code:
int[] ids= {1,2,3,4};
dataContext.Table.Where(c=>c.ids.Contains(t.id)).ToList();
Or
var result= (from p in dataContext.Table.AsEnumerable()
join q in ids on p.id equals q
select p).Distinct() .ToList();

Convert LINQ with Model To Array

I'm trying to create a LINQ to get the records in Personnel table that exist in Users table. Here's the tutorial I'm currently following: Convert the Results of a LINQ Query to an Array.
However, when I try to implement it in my codes I'm having an error: 'UserModel[]' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains<string>(IQueryable<string>, string)' requires a receiver of type 'IQueryable<string>'
var users = from u in db.USR_MSTR select new UserModel { emp_id = u.EMP_ID };
UserModel[] userList = users.ToArray();
var matches = from p in db.PERSONNEL_MSTR
where userList.Contains(p.EMP_ID) //userList is generating the error above
select p;
Contains is awaiting for UserModel instance to be passed, that's why you get error. Just use .Any() instead:
var matches = from p in db.PERSONNEL_MSTR
where userList.Any(u=> u.ID == p.EMP_ID)
select p;
What it does here is: If p.EMP_ID is found inside userList, than it is selected.
Actually you made a mistake in this
userList.Contains(p.EMP_ID)
userList is an IQueryable<UserModel> object, it not an IQueryable<string> array, on the other hand p.EMP_ID is a string, that the reason why you got that error.
You need to fix it as following
List<string> userIdList = users.Select(u => u.emp_id.ToString()).ToList();
var matches = from p in db.PERSONNEL_MSTR
where userIdList.Contains(p.EMP_ID)
select p;

NH QueryOver - use properties of main query in subquery

I am trying to convert following SQL to QueryOver:
Select 1
From myTable mt
Where mt.ForeignKey in (select ID from otherTable ot where ot.ID = R.ID)
I want to use this subquery inside an EXISTS / NOT EXISTS statement like:
select * from table R where .... AND EXISTS (query above)
Currently I have something like:
mainQuery.WithSubquery.WhereExists(QueryOver.Of<myTable>()
.Where(mt => mt.ForeignKey)
.WithSubquery.IsIn(QueryOver.Of<otherTable>().Where(c => c.Id == R.SomeId)));
I created this query as a subquery which I want to connect to the main query.
The problem is that the table aliased as R is the table called by the main query and I don´t know how to access columns of the table (NHibernate Model) R (which is not accesible in the query above), so my question is:
How can I get values from the main query and use them in a subquery. I think this is only possible by creating the subquery inline (as in mainQuery.WithSubquery.Where(..) or smth. similar) but I can´t see what would be the best possible way to do so. I appreciate any help!
Thanks in advance!
The trick is to use proper alias, for the parent query:
// the alias
myTable R = null;
mainQuery
.WithSubquery
.WhereExists(QueryOver
.Of<myTable>( () => R) // the Alias in place
.Where(mt => mt.ForeignKey)
.WithSubquery.IsIn(QueryOver.Of<otherTable>().Where(c => c.Id == R.SomeId)));
Note, not fully sure about the mainQuery part, but the solution in general here is like this:
// I. the outer query ALIAS
Employee emplyoee = null;
// II. the subquery - using the alias
var subQuery = QueryOver.Of<Contact>()
.Select(x => x.ID)
.Where(x => x.Related.ID == emplyoee.ID); // use alias
// III. declare the outer query and use the above alias
var query = session.QueryOver<Employee>(() => emplyoee) // declare alias
.WithSubquery
.WhereExists(subQuery); // put both together
Also check this for more ideas

How to convert Linq.ParallelQuery to Linq.IQueryable

var transactions = from t in context.Transactions
group t.Create_Date_Time by t.Participation_Id
into t1
select new { ParticipationId = t1.Key, CreateDateTime = t1.Max() };
var cases = from c in context.Cases
group c.Create_Date_Time by c.Participation_Id
into c1
select new { ParticipationId = c1.Key, CreateDateTime = c1.Max() };
var interactions = (from i in context.Interactions
join pp in context.Party_Participation on i.Party_Id equals pp.Party_Id
group i.Last_Update_Date_Time.HasValue ? i.Last_Update_Date_Time : i.Create_Date_Time by
pp.Participation_Id
into i1
select new {ParticipationId = i1.Key, CreateDateTime = i1.Max()}).AsQueryable();
Considering the above code, following will work
transactions.Union(cases);
However following will not work
transactions.Union(interactions);
Because transactions and cases both are returning Linq.IQueryable but the last one is Linq.ParallelQuery due to it join with an another table.
I need this functionality basically to make Union. interactions.Union(transactions) or transactions.Union(interactions) one with other.
The anonymous type of transactions and cases is the same. The anonymous type of interactions is different!
So the solution is to select in a way that makes the anonymous types the same. So either create your own type or convert the select product's properties to the same type.
Something like this should produce the same anonymous type for all the selects:
select new { ParticipationId = (int)c1.Key, CreateDateTime = (DateTime)c1.Max() }
My answer to this question may be incorrect however I raised up this question primarly for the following problem.
LINQ to Entities Union is throwing an error.
I found a fantastic reply from diceguyd30 and it was solved my problem. Hence I am closing this question in response to my previous question's answer.
interactions.Union(transactions.AsEnumerable());
that should work since the first parameter is IQueryable and the second is IEnumerable
Queryable.Union<TSource> Method (IQueryable<TSource>, IEnumerable<TSource>)

Cannot implicitly convert type 'System.Linq.IQueryable<int>' to 'int?'

var cityList = from country in
doc.Element("result")
.Element("cities")
.Descendants("city")
select new {
Name = country.Element("name").Value,
Code = country.Element("code").Value,
CountryCode = int.Parse(country
.Element("countrycode")
.Value)
};
foreach(var citee in cityList)
{
City city = new City();
city.CountryID = from cnt in db.Countries
where cnt.DOTWInternalID == citee.CountryCode
select cnt.ID;
}
I'm getting an error on the second query as seen in the title of this post. I tried converting to int to nullable int but nothing worked. Help me, guys.
Thanks
it will return an iQueryable, you will need to do something like using the First
cit.CountryID = db.Countries.First(a=>a.DOTWInternalID == citee.CountryCode).ID
It has elapsed a long time since the last update to the post but i think it's worth improving the solution.
In my opinion the solutions posted for this particular scenario are not the best way in terms of performace to get the ID you need. A better solution is as follows.
db.Countries.Where(a=>a.DOTWInternalID == citee.CountryCode)
.Select(a => a.ID).FirstOrDefault();
The previous statemants basically runs a SQL query similar to the following one:
SELECT TOP (1) ID
FROM [dbo].[Countries]
WHERE DOTWInternalID = 123
The proposed solutions work but basically do a "SELECT *" to create the entity with all the values and then obtain the ID from the object just created.
You can use Linqpad to actually see the generated SQL and tune up LINQ queries or Lambdas.
Hope it helps to some others that get to this post.
Here is the problem and solution
from cnt in db.Countries where cnt.DOTWInternalID == citee.CountryCode select cnt.ID part. If you omit the ID then it returns a Generic IEnumerable with Country(hoping that you have Country class). So what you have to do is first return the select criteria and select the first row then the ID field. Same like shown below.
cit.CountryID = (from cnt in db.Countries where cnt.DOTWInternalID == citee.CountryCode select cnt).First<Country>().ID;
This will solve your problem.
IQueryable is not a single int - but a query that can represent a collection.
As the error message says, your Linq query returns an System.Linq.IQueryable (for all intents and purposes a collection of ints). If you'd like to get one of them, you can either call First or ElementAt(n) to get the n'th element.
cit.CountryID = db.Countries.First(a=>a.DOTWInternalID == citee.CountryCode).ID

Categories

Resources