Linq To Sql 'Where Or' operator - linq-to-sql

I need to create a query which checks if a field (string) contains one or more words supplied at run time.
Basically I need to be able to ask a WhereOr question. This seems like it should be a common issue when dealing with LinqToSql.
I found the following reference but can't make sense out of it - and have no idea how to use it in my project.
i've tried the following loop:
var query = from d in context.Domains select d;
for (int i = 0; i < words.Length; i++)
{
query = query.Where(d => d.Name.Contains(words[i]));
}
but this builds a SQL query with WHERE AND Clauses NOT Where OR

I use PredicateBuilder for such things.
The predicate construction looks like this:
var query = from d in context.Domains select d;
var predicate = PredicateBuilder<Domains>.False();
for (int i = 0; i < words.Length; i++)
{
predicate = predicate.Or(d => d.Name.Contains(words[i]));
}
query = query.Where(predicate);

Related

Angular: Posting Data to a Table with a loop and giving a problem when posting the i of the loop into the table

Good day,
I am trying to get data into a table, with the tour_id and every single media_id (the station_id i am getting from somewhere else), the ordernumber is what is giving me a headache:
I am trying to get every station one number for every media i am posting.
For example:
station 1 has 2 medias
and station 2 has 3
then the odernumbers should be like this: 0, 0, 1, 1, 1
I am using the following Code at this moment:
for(var i = 0; i < this.currentStations.length; i++){
this.http.get("http://localhost:3000/mediasforstation/" + this.currentStations[i].id).subscribe((res) => {
medias = res;
for (var j = 0; j < medias.length; j++){
this.http.post("http://localhost:3000/posttourstations",
{"tour_id": id, "media_id": medias[j].id, "ordernumber": i}).subscribe(function(res) {
console.log(res);
}.bind(this));
}
});
}
Everything but the ordernumber works, however, the ordernumber always takes the number of stations involved, in our example above it would be 2.
How do I fix this?
Thank you very much for your help.
As I understand, you need to keep the index value. The type of variable i is var which is function scoped. Within outer loop, you are calling an API that returns some response, meanwhile the value of i is updated and for next index/counter, the API call has been sent. When you get response from API calls, you get the value of i where the outer loop has been called of.
In other words, you need to understand the difference between var and let. Your problem can be solved by replacing
for(var i=0;...)
with
for(let i=0;...)
Here's providing you the sample code.
//block scoped - retains value of i
for (let i=0;i<10;i++){
this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(res=>{
for(var j=0;j<5;j++){
console.log(`i=>${i}`)
}
})
}
//function scoped - gets updated value of i
for (var i=0;i<10;i++){
http.get('https://jsonplaceholder.typicode.com/users').subscribe(res=>{
for(var j=0;j<5;j++){
console.log(`i=>${i}`)
}
})
}

Entity framework updates several records when FirstOrDefault() is used

I have a rather strange problem which is scratching my head at the moment. I am using EF together with MySQL for a project and when I want to update a record on the database like this
using (var context = new MyDbContext())
{
var record = (from d in context.Dictionary where d.CompanyName == companyName && d.Name == "Logo" select d).FirstOrDefault();
record.Value = _path;
context.SaveChanges();
}
Then every record that has d.Name == "Logo" gets updated for some reason, which means that it ignores the d.CompanyName == companyName part. Anyone who has experienced the same problem or know how to solve it?
Thanks in advance.
Actually I don't use EF Provider for MySQL often but I suppose it works.
The problem can be splitted in 2 parts, a select and an update. The select is fine, if you need to see what is the query you can split the select statement like this
var query = (from d in context.Dictionary where d.CompanyName == companyName && d.Name == "Logo" select d);
var record = query.FirstOrDefault();
and have a look to query variable (just point it in debug mode).
About your issue the only reason that I can immagine is that you did not configure the Dictionary class in the right way.
I mean, when you run context.SaveChanges an Update query is generated using the Key definition of Dictionary (the Where part of the query). If the key definition is wrong, the where clause will be wrong.
Use this I hope this will help you.
using (var context = new MyDbContext())
{
var record = context.Dictionary.Where(x=> x.CompanyName == companyName && x.Name == "Logo").FirstOrDefault();
record.Value = _path;
context.SaveChanges();
}

in mysql we have SOUNDEX() or we can use SOUNDS LIKE for related / wrong spells or words matching so is their any thing like in BIGQUERY

in mysql we have
SOUNDEX()
and
SOUNDS LIKE
for related / wrong spellings or words matching in query
Is there anything like that or similar in BigQuery? Can BigQuery be used for such queries?
Using BigQuery User-Defined Functions (UDF) in JavaScript you can simply implement SOUNDEX function yourself.
Here is SQL statement for BigQuery that calculate SOUNDEX:
#standardSQL
CREATE TEMP FUNCTION SOUNDEX(name STRING)
RETURNS STRING
LANGUAGE js AS """
if (name == null) return null;
let s = [];
let si = 1;
let c;
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
let mappings = "01230120022455012623010202";
s[0] = name[0].toUpperCase();
for(let i = 1, l = name.length; i < l; i++) {
c = (name[i].toUpperCase()).charCodeAt(0) - 65;
if(c < 0 || c > 25) { continue; }
if(mappings[c] == '0') { continue; }
if(mappings[c] != s[si-1]) {
s[si] = mappings[c];
si++;
}
if(si > 3) { break; }
}
if(si <= 3) {
while(si <= 3) {
s[si] = '0';
si++;
}
}
return s.join("");
""";
SELECT SOUNDEX("John Doe"), SOUNDEX("Jon Do")
Credit: I took the original JavaScript code from Chris Webb blog post here and slightly change the coding syntax.
I've checked in the "Google BigQuery Analytics" book, and no, BigQuery does not have anything like "SOUNDEX()" (at least at the time of publishing).
You might want to check cloudSQL, which is a mysql server hosted on the cloud. I know there are some functions from mysql you can't use in the cloudSQL, but it would be worth looking into.
I realize this question was asked years ago, but for those who wander here as I did looking for answers, here you go.
BigQuery does now have SOUNDEX()
Here is the documentation

Running a loop for each mysql query result fields

queryResultArr is the array that olds mysql queries results, let say i have in my table two columns: doc_1_hits and doc_2_hits, but i don't know prior how much docs i have and i want to run a loop like you can see below: queryResultsArr[0].doc_i_hits instead of doc_1_hits.
i tried a: var str = 'doc_'+i+'_hits'; and then queryResultsArr[0].str but nothing..
for(var i = 1; i < 3; i++){
if(queryResultsArr[0].doc_i_hits > 0 && queryResultsArr[1].doc_i_hits == 0){
console.log(i);
}
}
I think you could use the array notation and do it like below because they work similar in this case.
var a = 'doc_'+i+'_hits';
queryResultsArr[0][a]

SQLBulkCopy with Identity Insert in destination table

I am trying to insert a Generic list to SQL Server with SQLBulkCopy,
And i have trouble wit Identity Field
I wan t my destination table to generate identity field
How should i handle this,
here is my code
using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
bulkCopy.BatchSize = (int)DetailLines;
bulkCopy.DestinationTableName = "dbo.tMyTable";
var table = new DataTable();
var props = TypeDescriptor.GetProperties(typeof(tBFFormularyStatusList))
//Dirty hack to make sure we only have system data types
//i.e. filter out the relationships/collections
.Cast<PropertyDescriptor>()
.Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
.ToArray();
foreach (var propertyInfo in props)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
}
var values = new object[props.Length];
foreach (var item in myGenericList)
{
for (var i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
exception
Property accessor 'ID' on object 'ProcessFlatFiles.DetailsClass' threw the following exception:'Object does not match target type.'
I have also tried
using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
Finally I got this worked this way
using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity))
{
bulkCopy.BatchSize = (int)DetailLines;
bulkCopy.DestinationTableName = "dbo.myTable";
bulkCopy.ColumnMappings.Clear();
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
.
.
.
.
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.WriteToServer(datatable);
}
I know this is an old question, but I thought it was worth adding this alternative:
(If you already have correct schema, can skip 1,2,3)
Perform a simple TOP 1 select from the table to return the a datatable with the destination table's schema
Use DataTable's Clone method to generate a datatable with same schema and no data
Insert your data into this table
Perform SqlBulkCopy's WriteToServer (if column orders match, then the identity values can be read. If the option isn't provided in SqlBulkCopy's constructor then the default is to ignore these values and let the destination provide them).
The important point is that if you have the columns in the correct order (including identity columns), everything is handled for you.