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
Related
I want to get list of records from an entity model (I'm using EF version 5) with a particular accountID. I'm being supplied with the tableName string (this has to be dynamic) and the accountID. I'm trying the following 2 methods but none of them is working (giving me errors on the IQueryable object 'table':
PropertyInfo info = _db.GetType().GetProperty(tableName);
IQueryable table = info.GetValue(_db, null) as IQueryable;
var query = table.Where(t => t.AccountID == accID)
.Select(t => t);
List <object> recList = ( from records in table
where records.AccountID == accID
select records).ToList<object>();
The var query = table.Where(....).Select(...) is the correct move as it allows reflection for the query builder at runtime. However, t.AccountID is an error because of the type of t remains unknown.
I've previously used a similar approach in LINQ to SQL, using System.Linq.Expressions.Expression, e.g.:
// NOT TESTED
var table=context.GetTable(dynamicTableName);
var theT=table.Experssion; // actually, I forget. DynamicExpression or MemberBinding? or
var theField=Expression.Field(theT, "AccountID"); // or dynamic name
var query=table.Where(Expression.Equal(theField, accID);
var recList=query.ToList<object>();
If your object has a common interface there is a simpler syntax:
IQueryable<MyInterface> table = context.GetTable("table") as IQueryable<MyInterface>;
var recList=from r in table
where table.AccountID == ac // if your AccountID is on MyInterface
select table;
If you only have a few tables to support, you could do this as well:
IQueryable<MyInterface> table;
if("table1"==tableName)
table=_db.table1
elseif("table2"==tableName)
table=_db.table2
elseif("table3"==tableName)
table=_db.table3
else
throw exception
I built a DynamicRepository for a project I am working on. It uses generic methods exposed through EF along with dynamic linq. It might be helpful to look at that source code here:
https://dynamicmvc.codeplex.com/SourceControl/latest#DynamicMVC/DynamicMVC/Data/DynamicRepository.cs
You can query the entity framework metadata workspace to get the type for a given table name. This link might help:
Get Tables and Relationships
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();
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?
I have the following 3 tables with their fields
Books(Id_Book | Title | Year)
Book_Themes (Id | Id_Book| Id_Theme)
Themes (Id_Theme| Title)
I also have an Giud array with Id_Themes
Guid [] themesArray = new Guid []{new Guid("6236c491-b4ae-4a2f-819e-06a38bf2cf41"), new Guid("06586887-7e3f-4f0a-bb17-40c86bfa76ce")};
I'm trying to get all Books containing any of the Theme_Ids from the themesArray
This is what I have so far which is not working. Not sure how to use Contains in this scnenario.
int index = 1; int size= 10;
var books = (from book in DB.Books
join bookWThemes in DB.Book_Themes
on book.Id_Book equals bookWThemes.Id_Book
where themesArray.Contains(bookWThemes.Id_Theme)
orderby book.Year
select book)
.Skip((index - 1) * page)
.Take(size);
I'm getting an error on themesArray.Contains(bookWThemes.Id_Theme): System.Guid[] does not contain a definition for Contains. Also I'm not sure where to put the Distinct
****UPDATE****
noticed that my Model had Id_Theme as nullable... I changed the DB and didn't reflect the changes on my model. So to answer the question if it's nullable just change the Contains line to themesArray.Contains(bookWThemes.Id_Theme.Value)... and with this change it works.
Thanks for all the help!.
It's strange that your LINQ query is breaking down on .Contains. All three of the forms IEnumerable<> and List<> work for me.
[Test]
public void Test43()
{
var a = new List<Guid>(){new Guid(),new Guid(),new Guid()};
a.Contains(new Guid()); // works okay
var b = (IEnumerable<Guid>)a;
b.Contains<Guid>(new Guid()); // works okay
b.Contains(new Guid()); // works okay
}
For the "distinct" question, put the call here:
select book)
.Distinct() // <--
.Skip((index - 1) * page)
Try casting the Guid[] to List<Guid> and then you can use Contains on it.
where themesArray.ToList().Contains(bookWThemes.Id_Theme)
I'm using a LINQ to CRM from Advanced Developer Extension for MS CRM 4.0. It works fine with direct queries. But I've got a problem when query looks like this:
var connectionString = #"User ID=u; Password=p; Authentication Type=AD; Server=http://crm:5555/UO";
var connection = CrmConnection.Parse(connectionString);
var dataContext = new CrmDataContext(connection);
var data = from u in dataContext.Accounts
select new
{
Id = u.AccountID,
Name = u.AccountName,
};
var r = from n in data
where n.Name.StartsWith("test")
select new
{
Id = n.Id
};
r.Dump();
it throws an InvalidOperationException "Cannot determine the attribute name."
It's fine when a condition is directly in first query:
var data = from n in dataContext.Accounts
where n.AccountName.StartsWith("test")
select new
{
Id = n.AccountID,
Name = n.AccountName,
};
I cannot find any useful information about this kind of error. Is it a bug in Xrm Linq Provider?
Thanks in advance for any help.
Try eager loading the initial query with a ToList() so the latter query over your anonymous type is then evaluated locally. I get this is far from ideal if you have a lot of accounts but it'll prove the point. You essentially have a solution anyway in the last statement.
This is because the first query isn't executed at all until you call .Dump() at which point the entire expression including the second query is evaluated as one (deferred execution) by the provider which then looks for an attribute of Name.