Using Entity Framework 4.3 in one of my data access classes I have generic a function like this
public List<Company> Query(Func<Company, bool> expression)
{
return MyDbContext.Instance().Company.Where(expression).ToList();
}
I use it from the bussines layer classes as MyDAL.Query(a => a.Name.Contains(textToSearch)).
Despite ofEntity Framework return the correct results, I don't know why it instead of generate a Sql query sentence with Where clause like "Where name like '%' + textToSearch + '%'", It generates a sql query sentence without a where clause query all the table rows. Obviously this is very inneficient.
By the other way if in my data access clases I write a method like this:
public List<Company> GetLikeName(string textToSearch)
{
return MyDbContext.Instance().Company.Where(a => a.Contains(textToSearch)).ToList();
}
It generates correctly a Sql with where like clause.
Why If I use my generic query to retrieve results from database especifying the expression to query from my bussiness classes it generates a Sql sentence without where clause?
Thanks
You need to pass the expression parameter as an Expression<>:
public List<Company> Query(Expression<Func<Company, bool>> expression)
If you just pass a Func<>, then IEnumerable.Where is called instead of IQueryable.Where, and it runs in code, not in SQL.
Related
I need to work with SqlExpression<T> in a private method but the result should be SqlExpression<TU> (due to my project context).
T and TU aims same structure (TU is a subset of T with some computed expressions)
I didn't find a way to convert SqlExpression<T> into SqlExpression<TU>.
In following code T = Product class and TU = Powder class.
// Sample code
private static SqlExpression<Powder> CreateDefaultExpression(IDbConnection db, IPowderListFilter request)
{
var ev = db.From<Product>()
// Joins are set here...
.Select(p => new
{
CustomRalId = Sql.As(p.CustomRalId, nameof(Powder.CustomRalId)),
Mass = Sql.As(Sql.Sum(p.Width * p.Height / 1000000) * 2 * Settings.LacqueringGramsPerSquareMeter / 1000, nameof(Powder.Mass))
});
// I need to do something like...
ev.ConvertTo<SqlExpression<Powder>>();
// or ...
return new SqlExpression<Powder>(ev);
}
You basically can’t, the typed SqlExpression is a query builder that you can’t just change the Type of and have it automatically erase and reapply all the mutations to the query builder using a different Type.
If reuse is the goal you’d need to use standard C# to DRY as much code as possible which won’t be much since all lambda expressions is typed to a different Type.
So, I'm working with ServiceStack, and know my way around a bit with it. I've used AutoQuery and find it indispensable when calling for straight 'GET' messages. I'm having an issue though, and I have been looking at this for a couple of hours. I hope it's just something I'm overlooking.
I have a simple class set up for my AutoQuery message:
public class QueryCamera : QueryDb<db_camera>
{
}
I have an OrmLite connection that is used to retrieve db_camera entires from the database. this all works just fine. I don't want to return a model from the database though as a result, I'd like to return a DTO, which I have defined as another class. So, using the version of QueryDb, my request message is now this:
public class QueryCamera : QueryDb<db_camera, Camera>
{
}
Where the Camera class is my DTO. The call still executes, but I get no results. I have a mapper extension method ToDto() set up on the db_camera class to return a Camera instance.
Maybe I'm just used to ServiceStack making things so easy... but how do I get the AutoQuery request above to perform the mapping for my request? Is the data retrieval now a manual operation for me since I'm specifying the conversion I want? Where's the value in this type being offered then? Is it now my responsibility to query the database, then call .ToDto() on my data model records to return DTO objects?
EDIT: something else I just observed... I'm still getting the row count from the returned dataset in AutoQueryViewer, but the field names are of the data model class db_camera and not Camera.
The QueryDb<From, Into> isn't able to use your Custom DTO extension method, it's used to select a curated set of columns from the executed AutoQuery which can also be used to reference columns on joined tables.
If you want to have different names on the DTO than on your Data Model, you can use an [Alias] attribute to map back to your DB column name which will let you name your DTO Property anything you like. On the other side you can change what property the DTO property is serialized as, e.g:
[DataContract]
public class Camera
{
[DataMember(Name = "Id")] // serialized as `Id`
public camera_id { get; set; } // populated with db_camera.camera_id
[DataMember]
[Alias("model")] // populated with db_camera.model
public CameraModel { get; set; } // serialized as `CameraModel`
}
I'm using AutoMapper 5.2. I currently have a mapping statement that looks as follows:
CreateMap<JeffreysOnline.Data.Customer, JeffreysOnline.Entities.Customer>()
.ForMember(s => s.CustomerWant, t => t.Ignore());
Both the Customer table and Customer entity have a field named BadChecks. In the database it's an int. I recently changed the type to a bool in my entity. AutoMapper is now giving me the following error:
Unable to create a map expression from Customer.BadChecks (System.Int16) to Customer.BadChecks (System.Boolean) Mapping types: Customer -> Customer JeffreysOnline.Data.Customer -> JeffreysOnline.Entities.Customer Type Map configuration: Customer -> Customer JeffreysOnline.Data.Customer -> JeffreysOnline.Entities.Customer Property: BadChecks
It seems AutoMapper doesn't know how to map from an int to a boolean. Is it possible for me to help AutoMapper with this?
It may be helpful to know that in my DAL, I'm using ProjectTo() to pass an IQueryable to another method that is attempting to access the data, and therefore the mapping is occurring (an error being generated). My DAL code looks like this:
return entityList.OrderBy(row => row.LastName).ProjectTo<Entities.Customer>();
Automapper 6.0.2 - works without any ForMember... null, 0 = false, values >= 1 are mapped to true.
In Automapper 6.0.2 - other way:
class nnnProfile : Profile
{
CreateMap<src, dst>()
.ForMember(d => d.Decision, opt => opt.ResolveUsing<CustomBoolResolver>());
}
Resolver:
public class CustomBoolResolver : IValueResolver<src, dst, bool>
{
public bool Resolve(src source, dst destination, bool destMember,
ResolutionContext context)
{
return source.Decision == 1;
}
}
but this is per Destination, so not much flexible.
According to this page:
http://taswar.zeytinsoft.com/automapper-mapping-objects-part-5-of-7-customresolver/
In past you could write a custom resolver with just Source and target type.
I don't think I would know how to map from int to a boolean.
If you do figure out how that should happen, you'll need to create a mapping from int to boolean.:
CreateMap<int, bool>().ProjectUsing(src => src != 0);
Completely guessing there. But since you're using ProjectTo, you'll need to use ProjectUsing so that the expression makes it allllll the way down to your DAL.
Remember, when using ProjectUsing, AutoMapper isn't actually executing the mapping. It's creating a LINQ "Select" expression that it passes down to your query provider (EF maybe?). So you'll need to make sure that whatever you use in your projection expression, EF can support translating that eventually into SQL.
I'm having problems sending parameters with the ArangoJS library and was wondering if anyone could help.
With the example below, it is possible to execute db.query if parameter values are in the query, but as soon as I try to use bindVars I get silent errors and I can't extract any error details.
var db = require('arangojs')("http://127.0.0.1:8529");
/*
The '_system' database contains a collection called 'test' that contains one document:
{
"a": 1,
"b": 2
}
*/
// This works
db.query('FOR t IN test FILTER t.a == 1 RETURN t')
.then((cursor) => {
cursor.all()
.then(vals => {
console.log("\nNo bindVars");
console.log(vals);
});
});
// This does not work
db.query("FOR t IN #first FILTER t.a == #second RETURN t", { first: "test", second: 1 })
.then((cursor) => {
cursor.all()
.then(vals => {
console.log("\nUsing bindVars");
console.log(vals);
});
});
I'm new to Node.js and ArangoDB and would love to be able to use properly parameterized queries.
I'm also assuming that this use of parameters protects you from SQL Injection style attacks?
Thanks!
The problem isn't with the JavaScript driver or Node, the problem is with the query itself:
FOR t IN #first FILTER t.a == #second RETURN t
In AQL collection names can't be injected with ordinary bind parameters. This is because you're not actually trying to use the parameter as a string value but to refer to a collection with that name. To quote the AQL documentation:
A special type of bind parameter exists for injecting collection names. This type of bind parameter has a name prefixed with an additional # symbol (thus when using the bind parameter in a query, two # symbols must be used).
In other words, in AQL it has to be called ##first (instead of #first) and in the bind parameters argument to db.query it has to be called #first (instead of just first).
When using arangojs it's actually possible to avoid this entirely by using the aqlQuery template handler:
var aqlQuery = require('arangojs').aqlQuery;
var first = db.collection('test');
var second = 1;
db.query(aqlQuery`
FOR t IN ${first}
FILTER t.a == ${second}
RETURN t
`).then(
cursor => cursor.all()
).then(vals => {
console.log('Using aqlQuery');
console.log(vals);
});
This way you don't have to think about bind parameter syntax when writing queries and can write more complex queries without having to mess with extremely long strings. Note that it will recognize arangojs collection instances and handle them accordingly. Using a string instead of a collection instance would result in the same problems as in your example.
Additionally note that the template handler also exists in the arangosh shell and in ArangoDB itself (e.g. when using Foxx).
I am building a service using ServiceStack and using OrmLite to communicate with database. I found following example in ServiceStack OrmLite Documention:
db.Select<Author>(q => q.Earnings <= 50);
OR
db.Select<Author>(q => q.Name.StartsWith("A"));
I am trying it with my class User, but unable to find a overload for method "Select" which allows me to do mentioned stuff. In my case q is a linq expression not an instance/reference for generic class type (User in my case). Following is my code:
db.Select<User>(q => q.Where(x => x.LastName == "XYZ"));
and i want it to be like:
db.Select<User>(q => q.LastName == "XYZ");
Please let me know if that is an extension method which i am looking for and how can i use that?
The Type that gets selected is the table is looking at, e.g:
db.Select<Author>(...) //Author
db.Select<User>(...) //User
See the answers on this earlier question for selecting a subset of data with OrmLite.