Dyamic Linq .Net 4 error 'userid' could not be resolved in the current scope or contex - linq

I am trying to use Dynamic Linq library in my code, but it gives this error
'UserId' 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. Near simple identifier, line 6, column 1
and here is my code
TestDB db = new TestDB();
string filter = "UserId == 15";
//var searchResult =
GridView1.DataSource = from x in db.SearchSummaries.Where(filter)
select x;
GridView1.DataBind();

Not so familiar with dynamic Linq but from your error message:
'UserId' 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. Near simple
identifier, line 6, column 1
Please try this:
1.) Is the column UserId a Integer and not a String? Mabye you need to use:
string filter = "UserId='15'";
2.) Try to pass in the filter parameter as a second argument:
GridView1.DataSource = db.SearchSummaries.Where("UserId = #0", 15);
3.)
I don't know if you are able to run "regular" Linq queries, but if you are, try:
GridView1.DataSource = db.SearchSummaries.Where(search => search.UserId == 15);
GridView1.DataBind();

Try this:
TestDB db = new TestDB();
string filter = "xi => xi.UserId == 15";
//var searchResult =
GridView1.DataSource = from x in db.SearchSummaries.Where(filter)
select x;
GridView1.DataBind();
Or this:
TestDB db = new TestDB();
string filter = "UserId=15";
//var searchResult =
GridView1.DataSource = from x in db.SearchSummaries.Where(filter)
select x;
GridView1.DataBind();
EDIT: I realize this isn't dynamic linq...but it should work regardless as long as your data structure is correct. Could you post that?

Related

object reference not set error in mvc5

i am using viewmodel to display data from two tables (Eta and Voyage) and i have used viewmodel name as 'EtaVoyage'.The problem is when i use this query, it gives me this error
Additional information: Object reference not set to an instance of an object.
var Test = db.Etas.AsEnumerable().Select(v => new EtaVoyage()
{
ShippingAgent = v.ShippingAgent,
VesselInformation = v.VesselInformation,
Port = v.Port,
CPort = v.CPort,
EtaDate = v.EtaDate,
GoodsCarried = v.VoyageDetails.FirstOrDefault().GoodsCarried,
VoyagePurpose = v.VoyageDetails.FirstOrDefault().VoyagePurpose
}).ToList();
return View(Test);
But when i comment the last two fields related to voyagedetails, it is working fine.
var Test = db.Etas.AsEnumerable().Select(v => new EtaVoyage()
{
ShippingAgent = v.ShippingAgent,
VesselInformation = v.VesselInformation,
Port = v.Port,
CustomPort = v.CustomPort,
EtaDate = v.EtaDate,
// GoodsCarried = v.VoyageDetails.FirstOrDefault().GoodsCarried,
// VoyagePurpose = v.VoyageDetails.FirstOrDefault().VoyagePurpose
}).ToList();
return View(Test);
i need to display these two columns too in the index page.
FirstOrDefault() might return null,
Enumerable.FirstOrDefault : Return Value
Type: TSource
default(TSource) if source is empty; otherwise, the first element in source.
Use
.Select(i=>i.GoodsCarried).FirstOrDefault()
....
GoodsCarried = v.VoyageDetails.Select(i=>i.GoodsCarried).FirstOrDefault(),
VoyagePurpose = v.VoyageDetails.Select(i=>i.VoyagePurpose).FirstOrDefault()
}).ToList();
The collection v.VoyageDetails must not contain any items, and therefore FirstOrDefault is returning the default (null for reference types). You can handle this special case separately, or, since you seem to just be flattening a collection, you can use a null-conditional operator to set GoodsCarried and VoyagePurpose to null when FirstOrDefault returns null.
GoodsCarried = v.VoyageDetails.FirstOrDefault()?.GoodsCarried,
VoyagePurpose = v.VoyageDetails.FirstOrDefault()?.VoyagePurpose
Note it is also possible that:
v.VoyageDetails itself is null, depending on how your class is initialized and data is loaded. If this is expected, you may need to handle this case as well. Again with the null-conditional operator:
GoodsCarried = v.VoyageDetails?.FirstOrDefault()?.GoodsCarried,
VoyagePurpose = v.VoyageDetails?.FirstOrDefault()?.VoyagePurpose
If you are using an ORM such as Entity Framework, the VoyageDetails collection is not eagerly loaded, it may simply not be retrieving the data for you. If this applies, you need to explicitly load the data in the collection. In Entity Framework this is done with an Include call. Note your AsEnumerable() call will stop Linq-To-Sql from optimizing this into a single query, but I assume this is intentional:
db.Etas.Include(x => x.VoyageDetails).AsEnumerable().Select(...)

Linq Query Message: Specified cast is not valid

Following are the columns name and its data type:
TemplateName string
TaskName string
AvgDays string (but contains int values)
my LINQ query:
DataTable newTable = new DataTable();
newTable = (from r in table.AsEnumerable()
group r by r.Field<string>("TemplateName") into templates
let totalDays = templates.Sum(r => r.Field<int>("AvgDays"))
from t in templates
group t by new
{
TemplateName = templates.Key,
TaskName = t.Field<string>("TaskName"),
TotalDays = totalDays
} into tasks
select new
{
tasks.Key.TemplateName,
tasks.Key.TaskName,
AvgDays = tasks.Sum(r => r.Field<int>("AvgDays")),
tasks.Key.TotalDays
}).CopyToDataTable();
I am getting error after execution of query. Error is "Specified cast is not valid.".
Please let me know where am I doing wrong.
I guess Field<int> causes the problem, because the field is not really an int. As you said before, it's a string.
Try following
AvgDays = tasks.Sum(r => int.Parse(r.Field<string>("AvgDays"))),
Field<T> does not perform some magic transformation between different types. It's implemented like that:
return (T)((object)value);
In practice there is a little bit more code, but logic is the same. It just tried to cast your value to desired type, and as you probably know, casting string to int does not work.

mvc3 dapper No mapping exists from model

I am doing some coding in dapper and I get the error No mapping exists from object type to a known managed provider native type this error occurs on the myfriends var for dapper . I am using dapper to get a list of INT values from a table then comparing them against another.. this is the code that gives me that error
int myid = Convert.ToInt32(User.Identity.Name);
// The var myfriend is giving me that error above
var myfriends = sqlConnection.Query<friend>("Select otherfriendsID from friends where profileID=#myidd", new { myidd = myid }).ToList();
var profiles = sqlConnection.Query<profile>("Select top 40 * from profiles where photo is not null AND profileID=#friendship order by profileID desc", new {friendship=myfriends}).ToList();
however if I use entity everything works fine for instance this code below works..
var myfriends = (from s in db.friends where s.profileID == myid select s.otherfriendsID).ToList();
What could be going on here..
myfriends is a List<friend>. You then pass that in as a query parameter, i.e.
new {friendship=myfriends}
with:
AND profileID=#friendship
Now... what is #friendship ? How should it pass in a List<friend> here? What does that even mean to pass in a list of objects (each of which could have multiple properties) as a single parameter? (note: I'm ignoring table-valued-parameters for the purposes of this question)
So: how many myfriends do you expect? 0? 1? any number? This could be, for example:
var profileIds = myfriends.Select(x => x.ProfileId);
...
new {profileIds}
...
AND profileID in #profileIds
or maybe:
new {profileId = myfriends.Single().ProfileId}
...
AND profileID = #profileId

Avoid "Parameterless Queries Error" with Linq Let clause

I'd like my Linq query to create an additional column in the results on the fly. In this case the column is a Class object I created that will contain image info. I was wondering what the right way is of doing this:
var validPics = (from x in db.picsVotesTagsJs let picObj = new CarShowImages(x.picname) where x.enabled == 1 select x).Take(25);
var myArray = validPicSummaries.ToArray();
Line 2 gerenates the error:
Only parameterless constructors and initializers are supported in LINQ to Entities.
This is my first time using the Let clause. My queries are usually pretty simple.
Create parameterless constructor and use some public property (e.g. PicName) to set picture name to your CarShowImages object:
var validPics = (from x in db.picsVotesTagsJs
where x.enabled == 1
select new CarShowImages { PicName = x.picname }).Take(25);
var myArray = validPics.ToArray();

Linq to NHibernate Distinct() "Expression type not supported" error

I've got the following code:
var data = (from v in this.GetSession().Query<WorkCellLoadGraphData>()
where v.WorkCellId == "13"
select
new WorkCellLoadGraphData
{
RowId = v.RowId,
WorkCellId = v.WorkCellId,
WorkCellName = v.WorkCellName,
WorkCellGroupId = v.WorkCellGroupId,
WorkCellGroupName = v.WorkCellGroupName
});
return data.Distinct();
If I don't call the Distinct() extension method, I have no issues whatsoever. However, if I do call the Distinct() method, I get the following error:
Expression type 10005 is not supported
by this SelectClauseVisitor.
After some searching I came across this:
https://nhibernate.jira.com/browse/NH-2380
But as you can see I'm not returning an anonymous type.
Has anyone else come across this issue? If so, how did you solve it?
David
Could this work? By using an anonymous type in the query, you would allow NHibernate to make the distinct query in the database. When using your own type, the comparison must be used with the class' Equals method.
var data = (from v in this.GetSession().Query<WorkCellLoadGraphData>()
where v.WorkCellId == "13"
select
new
{
v.RowId,
v.WorkCellId,
v.WorkCellName,
v.WorkCellGroupId,
v.WorkCellGroupName
})
.Distinct()
.Select (v =>
new WorkCellLoadGraphData{
RowId = v.RowId,
WorkCellId = v.WorkCellId,
WorkCellName = v.WorkCellName,
WorkCellGroupId = v.WorkCellGroupId,
WorkCellGroupName = v.WorkCellGroupName});

Resources