How can I resolve error : Linq query cannot be translated.? - entity-framework

#Karney. this is my code
var customerMachineId = wcDataContext.Customers.Where(x =>
x.UserId.Equals(currentUser.Result.Id)).Select(x =>
x.MachineId).ToList();
var customers1 = (from customer in wcDataContext.Customers
join machine in wcDataContext.Machineinfo
on customer.MachineId equals machine.MachineId
where customerMachineId.Contains(customer.MachineId)
select new UserMachineInfo
{
Mac1 = machine.Mac1,
Mac2 = machine.Mac2,
MachineId = machine.MachineId,
MachineName = machine.MachineName,
UserId = customer.UserId,
UserName = customer.User.FirstName.ToString() + " " + customer.User.LastName.ToString()
//UserName = (customer.User.FirstName + " " + customer.User.LastName).ToString()}
.OrderBy(ti => ti.Inner.FirstName.ToString() + " " + ti.Inner.LastName.ToString())' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToList.
The error is given while querying data in jQuery datatables. I was trying to search data in a jQuery datatable. How can I rewrite this query to resolve error?

Related

How to loop through an array of strings Gatling during scenario building

I'm trying to loop through an array of products (Strings) in order to execute a call for each of them but I'm mismatching some types during scenario building, here is an example of what I'm trying to do:
val createAddToCart: ScenarioBuilder = scenario("Add to cart").exec(CartRequest.addToCart())
This is my CartRequest object:
def addToCart(): Unit (???) = {
for (product <- products) {
addToCart(product)
}
}
def addToCart(productId:String): ChainBuilder =
{
exec(http("addToCart")
.post(addToCartUrl)
.headers(authHeaders)
.body(generateRequestBodyForProduct(productId)).asJson
.check(bodyString.saveAs("body"))
).exec(
session => {
body = session("body").as[String]
println("response body " + body)
session
}
)
}
def generateRequestBodyForProduct(productId: String): Body with (Expression[String]) =
{
StringBody("{ \"productId\": \"" + productId + "\"," +
" \"qty\": " + 1 + " , " +
"\"storeId\": \"" + storeId + "\"}")
}
Obviously, I'm having problems calling CartRequest.addToCart() due to type mismatching (Unit to ChainBuilder).
Is there a way to execute and return the addToCart method as a list of scenarios?
I hope I explained myself well.
Thanks for your time.
First, you don't look like a Scala developper. You should probably use the new Java DSL available since Gatling 3.7.
Then, you're not using the Gatling constructs properly.
your for loop should be a Gatling foreach instead
the dynamic productId in your request body should be resolved with Gatling Expression Language => "{ \"productId\": \"#{productId}\", \"qty\": " + 1 + " , " + "\"storeId\": \"" + storeId + "\"}"

Making raw SQL safe in Entity Framework

var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");
// normally when using parameters I would do something like this:
var valueParam = SqlParameter("aValue", passedInValues);
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE Column1 = #aValue", valueParam);
// NOTE: I would not do this at all. I know to use LINQ. But for this question, I'm concentrating on the issue of passing variables to a raw sql string.
But since both the column and value are "parameters" in:
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");
, is there to prevent sql injection for both?
First: whilelist aColumn: this has to be added via string concatenation but you know what columns are in your database (or you can check using schema views).
Second: In entity framework – as you show – you can use parameters for values in the query. However, rather than creating SqlParameter instances you can pass the values and use #p0, #p1, ….
Right way to prevent SQL injection is to use SqlParameter and SqlQuery<T>:
var parameter = new SqlParameter("#title", value);
var result = context.Database.SqlQuery<Book>("SELECT * FROM Books WHERE Title LIKE #title", parameter);
http://ignoringthevoices.blogspot.ru/2013/07/sql-injection-with-entity-framework-5.html

OrientDB Functions Management questions

I am trying to generate some mock data via a function, basically some edges between a "Department" and "Employee" Vertex.
Here is the code:
var employees = gdb.command('sql', 'select * from Employee', []);
var departments = gdb.command('sql', 'select * from Department', []);
for (var i = 0; i < employees.length; i++) {
var emp = employees[i];
var department = departements[Math.round(Math.random()*(departements.length - 1))];
var e = "create edge employee_belong_dpartement from #" + emp['#rid'] + " to " + department['#rid'];
gdb.command('sql',e, []);
}
gdb.commit();
Could someone explain me why I can't get this to work ?
When I log emp['#rid'] I get nothing back, I can't seem to read the "id" or any other value.
Please help me understand what is going on in the console as its hard to debug thanks
employees contains ODocument objects, so to extract fields you should use .field() method. To get the identity ODocument has .getIdentity() method. Example:
var e = "create edge employee_belong_dpartement from #" + emp.getIdentity() + " to " + department.getIdentity();
Lvc#

Mongo dbref additional fields are invisible in mongoshell. How to display them?

Background: This problem came up with Doctrine ODM, that uses a _doctrine_class_name field in DBRefs that is invisible in the Mongo shell (2.2.2) and caused quite a culprit, when we had to update a record manually.
Example:
mongoshell> use testdb; // for safety
mongoshell> a = DBRef("layout_block", ObjectId("510a71fde1dc610965000005")); // create a dbref
mongoshell> a.hiddenfield = "whatever" // add a field that's normally not there like Doctrine does
mongoshell> a // view it's contents, you won't see hiddenfield
mongoshell> for (k in a) { var val = a[k]; print( k + "(" + typeof(val) + "): " + val ); } // you can see that there's more if you iterate through it
mongoshell> db.testcoll.save({ref: [ a ]}) // you can have it in a collection
mongoshell> db.testcoll.findOne(); // and normally you won't see it
Without an iteration like the third command from below (or MongoVue), you won't ever know there's more in a DBRef if you simply use find(). I have not found any usable modifier for find()(tried: toArray, tojson, printjson, toString, hex, base64, pretty, chatty, verbose, ...).
Has anybody got a method to display DBRef contents verbosely in mongo shell?
The Mongo shell is an extension of Mozilla SpiderMonkey (1.7?) and has pretty bare bones functionality.
The suggestion from a MongoDB blog post on the shell is to define the following inspect function in .mongorc.js in your home directory
function inspect(o, i) {
if (typeof i == "undefined") {
i = "";
}
if (i.length > 50) {
return "[MAX ITERATIONS]";
}
var r = [];
for (var p in o) {
var t = typeof o[p];
r.push(i + "\"" + p + "\" (" + t + ") => " +
(t == "object" ? "object:" + inspect(o[p], i + " ") : o[p] + ""));
}
return r.join(i + "\n");
}
Additionally you can redefine the DBRef.toString function as something like:
DBRef.prototype.toString = function () {
var r = ['"$ref": ' + tojson(this.$ref), '"$id": ' + tojson(this.$id)];
var o = this;
for (var p in o) {
if (p !== '$ref' && p !== '$id') {
var t = typeof o[p];
r.push('"' + p + '" (' + t + ') : ' +
(t == 'object' ? 'object: {...}' : o[p] + ''));
}
}
return 'DBRef(' + r.join(', ') + ')';
};

can i use custom lambda method in entity framework?

i have some methods like:
public static string ToOtherFormat (this string inp)
{
// some code to change inp
return inp;
}
and in my select i want to have code like this:
var DetailMembers = db.TB_Members
.Where(x=> x.FName == obj.ToOtherFormat())
.Select( x=> new { name = (x.FName.ToOtherFormat() + " " + x.LName) , x.ActCode });
i try and just have error. is it possible?
thanks!
i receive this error in simple convert to integer
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
with this code
.Where(x => x.MemberID == Convert.ToInt32(Hmemid.Hash_two_Decrypt())
Looks like you are querying against the database. Your current query will get translated into SQL query and since SQL doesn't recognize your function that is why you get error.
You may get the data from the tables using a query without that function and then later do the formatting on the result set.
i found it on use .AsEnumerable() method like:
var DetailMembers = db.TB_Members.AsEnumerable()
.Where(x=> x.FName == obj.ToOtherFormat())
.Select( x=> new { name = (x.FName.ToOtherFormat() + " " + x.LName) , x.ActCode });