Problem
In LINQPad 4, when I try to run the following code:
void Main()
{
using (var conn = new SQLiteConnection(#"C:\linqToSqlite"))
{
var query = new SQLiteCommand(conn);
query.CommandText = "SELECT * FROM MyTable";
var result = query.ExecuteQuery<MyTable>();
}
}
I receive the following error:
'System.Data.SQLite.SQLiteCommand' does not contain a definition for 'ExecuteQuery' and no extension method 'ExecuteQuery' accepting a first argument of type 'System.Data.SQLite.SQLiteCommand' could be found (press F4 to add a using directive or assembly reference)
What I have tried
Additional References:
System.Data.Linq.dll
System.Data.SQLite.dll
System.Data.SQLite.Linq.dll
Additional Namespace Imports:
System.Data.Linq
System.Data.SQLite
System.Data.SQLite.Linq // Cannot add this, cleanup removes it.
I've also found documentation, which talks about using the SQLiteCommand.ExecuteQuery method. That's the only place I have seen the command mentioned.
Don't think this feature is built-in. Whenever I need to do execute a direct sql query against a sqlite database, I add a Nuget reference to Dapper and add the namespace Dapper. This then allows me to do something like.
string query = "Select * from MyTable" ;
var results = this.Connection.Query<MyTable>(query).ToList();
or
using (var conn = new SQLiteConnection(#"C:\linqToSqlite"))
{
string query = "Select * from MyTable" ;
var results = conn.Query<MyTable>(query).ToList();
}
From your given document I find you can consider using it by referring RebornBuddy.exe Version: 1.0.233.0 (1.0.233).
This is an image:
And the SQLLite.dll's ExecuteQuery() just uses no "generic type". So it's ONLY used in a common ado.net. And if you insist using that in LINQ (and if that's implemented). Maybe you can use something like "SqlLiteDataContext's ExecuteQuery".
For more about SqlLiteDataContext's ExecuteQuery, please see this in detailled info:
https://msdn.microsoft.com/en-us/library/bb361109(v=vs.110).aspx
Related
I'm trying to do a Dynamic LINQ like in the ScotGu's blog
var select = db.San_Imovel.Where("Imovel_Id = #0", 123).Select("new(Imovel_Id)");
but I get the error
the best overloaded method match for '.Where(string, System.Data.Objects.OBjectsParameter[])' has some invalid arguments
Are you using .net 3.5?
Note that only 3.5+ supports that syntax.
Use String.Format:
var select = db.San_Imovel.Where(String.Format("Imovel_Id = {0}", 123)).Select("new(Imovel_Id)");
What is that 123 for? In order for this to compile, it will probably need to look like one of these:
var select = db.San_Imovel.Where("Imovel_Id = #0").Select("new(Imovel_Id)");
OR
var select = db.San_Imovel.Where("Imovel_Id = #0 AND SomethingElse = 123").Select("new(Imovel_Id)");
An old question for Linq 2 Entities. I'm just asking it again, in case someone has came up with the solution.
I want to perform query that does this:
UPDATE dbo.Products WHERE Category = 1 SET Category = 5
And I want to do it with Entity Framework 4.3.1.
This is just an example, I have a tons of records I just want 1 column to change value, nothing else. Loading to DbContext with Where(...).Select(...), changing all elements, and then saving with SaveChanges() does not work well for me.
Should I stick with ExecuteCommand and send direct query as it is written above (of course make it reusable) or is there another nice way to do it from Linq 2 Entities / Fluent.
Thanks!
What you are describing isnt actually possible with Entity Framework. You have a few options,
You can write it as a string and execute it via EF with .ExecuteSqlCommand (on the context)
You can use something like Entity Framework Extended (however from what ive seen this doesnt have great performance)
You can update an entity without first fetching it from db like below
using (var context = new DBContext())
{
context.YourEntitySet.Attach(yourExistingEntity);
// Update fields
context.SaveChanges();
}
If you have set-based operations, then SQL is better suited than EF.
So, yes - in this case you should stick with ExecuteCommand.
I don't know if this suits you but you can try creating a stored procedure that will perform the update and then add that procedure to your model as a function import. Then you can perform the update in a single database call:
using(var dc = new YourDataContext())
{
dc.UpdateProductsCategory(1, 5);
}
where UpdateProductsCategory would be the name of the imported stored procedure.
Yes, ExecuteCommand() is definitely the way to do it without fetching all the rows' data and letting ChangeTracker sort it out. Just to provide an example:
Will result in all rows being fetched and an update performed for each row changed:
using (YourDBContext yourDB = new YourDBContext()) {
yourDB.Products.Where(p => p.Category = 1).ToList().ForEach(p => p.Category = 5);
yourDB.SaveChanges();
}
Just a single update:
using (YourDBContext yourDB = new YourDBContext()) {
var sql = "UPDATE dbo.Products WHERE Category = #oldcategory SET Category = #newcategory";
var oldcp = new SqlParameter { ParameterName = "oldcategory", DbType = DbType.Int32, Value = 1 };
var newcp = new SqlParameter { ParameterName = "newcategory", DbType = DbType.Int32, Value = 5 };
yourDB.Database.ExecuteSqlCommand(sql, oldcp, newcp);
}
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.
I've got a situation where I need to use a custom expression in a LINQ to Entities query (because I want to have custom logic that L2E wouldn't otherwise understand:
var query = db.MyTable.Where(MyPredicateExpression)
But I'd rather use query comprehension syntax:
var query = from x in db.MyTable where [x matches the predicate of MyPredicateExpression]
I know this is possible, because L2E supports it in other places:
var query = from x in db.MyTable where x.Length > 10
How do they make that work?
Edit: I'm using devart's LinqConnect for Oracle, which may behave somewhat differently than Microsoft L2E.
Entity Framework and LINQ to SQL do not support this scenario, because the translation of MyPredicateExpression should be added to expression tree translator.
I recommend you to create a stored function performing the predicate check and add this function to DataContext. You will be able to use a query like the following in this case:
var query = from x in db.MyTable where context.MyPredicateFunction(x.Field) select x;
Update. Here is the updated query that takes into account your comments:
int[] values = new int[] { 1, 2, 3 };
var query = from x in db.MyTable where values.Contains(x.AuditState) select x;
Update 2. You can add a Queryable property to your context that will be obtaining the necessary set of MyTable objects as shown in the following example:
public partial class MyDataContext {
IQueryable<MyTable> GetSpecialTables {
get {
int[] values = new int[] { 1, 2, 3 };
return this.MyTables.Where(x => values.Contains(x.AuditState));
}
}
}
Replace MyDataContext with the actual name of your context.
If I understand the problem correctly, you can either use an extension method OR call a function that returns a bool.
I use linq to access a table from my DB using Entity Framework
MyDBEntities context = new MyDBEntities;
int id = 111;
var item = context.MyTable.Where(i => i.id == id).Single();
This works fine but now I create a method I wish to use instead of the id check:
bool AreNear(string Adress, object Adress)
I'd like to use that way
string adress = "...";
var item = context.MyTable.Where(i => AreNear(i.adress,adress) ).Single();
but I get an error at the execution saying I can't use the method in my query
is there a way to make it work?
Unfortunately, there is no way to make it work.
The reason for this is that the LINQ query isn't really executed as .NET code but it is translated into SQL by the EF provider. This EF provider doesn't know how to translate AreNear into SQL, so it fails.