How to search multi keywork in linq query - entity-framework

i have this code in homepage
CheckBox[] ch= new CheckBox[12];
ch[0] = ChkContextA;
ch[1]= ChkContextB;
ch[2]= ChkContextC;
ch[3]= ChkContextD;
ch[4]= ChkContextE;
ch[5]= ChkContextF;
ch[6]= ChkContextG;
ch[7]= ChkContextH;
ch[8]= ChkContextI;
ch[9]= ChkContextJ;
ch[10]= ChkContextK;
ch[11]= ChiContextL;
for (int i = 0; i < 11; i++)
if (ch[i].Checked) search += ch[i].Text + " ";
Response.Redirect("SearchEstate.aspx?content="+search);
and this code in SearchEstate
var content = Request.QueryString["content"];
RealEstateEntities db = new RealEstateEntities();
var query = from O in db.Owners
join E in db.Estates on O.OwnerID equals E.OwnerID
join P in db.Properties on E.PropertyID equals P.PropertyID
where P.Facilities.Contains(content)
select new
{
regdate = E.RegisterDate,
region = E.Region,
Estype = E.EstateType,
Fac = P.Facilities,
deal = P.DealType,
price = P.TotalCost,
img = E.Picture,
addrss = O.Address,
area = P.Area,
tel = P.TellNum,
bed = P.RoomNum,
park = P.ParikingNum
};
Repeater2.DataSource = query.OrderByDescending(x => x.regdate);
Repeater2.DataBind();
when user checked some checkbox "content" for example have this value:
SearchEstate.aspx?content=ContextB ContextE ContextJ
I Want search this values in Facility field in db
How can I do this? (Sorry for my bad English)

I have the feeling your are looking for something along the lines of this query:
var content = Request.QueryString["content"];
string[] contentArray = content.Split(' ');
//...
var query = //...
where P.Facilities.Any(f => contentArray.Contains(f.FacilityName))
//...
(or instead of FacilityName some other property of Facility)
But I am not sure.

Related

Accent insensitive in filter backend to datatable in ASP.NET MVC 5

I made a method on the back-end side to handle the filter of my datatable.
On the other hand, this one does not manage the accents of the French language, so if I have "école" and I write "ecole" it cannot find it.
I found this method on another question on stackoverflow
public static String RemoveDiacritics(this String s)
{
String normalizedString = s.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < normalizedString.Length; i++)
{
Char c = normalizedString[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
and it works, but only for part of my problem. It works on the letter or the word that is written in the search, but I am not able to apply it in my linq query, so with the .RemoveDiacritics() method my "école" becomes "ecole", but I don't am not able to apply it in the column of my table and it always looks for "école".
Here the code for the search:
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.UsagerId == IdFilter || x.Niveau == IdFilter);
}
else if (search != "")
{
// this line work
textFilter = search.ToLower().RemoveDiacritics();
// This is the full line, but absolutely takes the accents out to get the right information out
// query = query.Where(x => x.Nom.ToLower().Contains(textFilter) || x.Prenom.ToLower().Contains(textFilter) || x.Username.ToLower().Contains(textFilter) || x.Email.ToLower().Contains(textFilter) || x.EtabNom.ToLower().Contains(textFilter) || x.ActifStatut.ToLower().Contains(textFilter));
// This is the line that will replace the line above, which I try and it doesn't work ( this part: x.Prenom.ToLower().RemoveDiacritics())
query = query.Where(x => x.Prenom.ToLower().RemoveDiacritics().Contains(textFilter));
}
}
This is the basic query:
IQueryable<ListeUsagers> query = (from u in db.USAGERs
join e in db.ETABLISSEMENTs on u.USAGER_INST equals e.ETAB_CODE
where u.USAGER_INST == instId && u.USAGER_NIVEAU > 3 && u.USAGER_NIVEAU < 5 //&& u.USAGER_ACTIF == 1
select new ListeUsagers()
{
UsagerId = u.USAGER_id,
Nom = u.USAGER_NOM,
Prenom = u.USAGER_PRENOM,
EtabCode = e.ETAB_CODE,
EtabNom = e.ETAB_NOM_COURT,
EtabType = e.ETAB_TYPE,
Niveau = u.USAGER_NIVEAU,
Username = u.USAGER_USERNAME,
UserPassword = u.USAGER_MP,
DateCreation = u.USAGER_DATE_INSC,
Sexe = u.USAGER_SEXE,
Lang = u.USAGER_LANGUE,
Telephone = u.USAGER_TELEPHONE,
Email = u.USAGER_EMAIL,
FonctionTravail = u.USAGER_FONCTION,
LieuTravail = u.USAGER_LIEUTRAVAIL,
Note = u.USAGER_NOTE,
Actif = u.USAGER_ACTIF,
ActifStatut = u.USAGER_ACTIF == 0 ? "Inactif" : "Actif"
});
This is the error:
LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System.String)' method, and this method cannot be translated into a store expression.
There's built-in functionality to do this in entityframework: https://learn.microsoft.com/en-us/ef/core/miscellaneous/collations-and-case-sensitivity if you're using EF 5+
You'll want an accent insensitive collation ("AI", not "AS" in the examples on that page.)

Creating OBX segments from multiple DB rows

I have a DB source which I am transforming into HL7. In the transform, I have a step to connect to the database and retrieve rows for OBX segments, there can be no rows or multiple rows.
I'm successfully getting all the values, but I'm having trouble getting them written into OBX segments. They're all the same, and all the last row retrieved.
Database values:
OBX3 OBX5
Test123 This is a new referral
Test456 Person
Test789 Anxiety
The result I'm getting in the message is:
OBX|0||Test789||Anxiety
OBX|1||Test789||Anxiety
OBX|2||Test789||Anxiety
Code:
var erefID = msg['erefid'].toString();
var dbConn = DatabaseConnectionFactory.createDatabaseConnection(driver,address,username,password);
var sql = "SELECT OBX3,OBX5 from table where column =" + erefID;
var results = dbConn.executeCachedQuery(sql);
var resultSize = results.size();
logger.info('query results ' + results);
logger.info('result size ' +resultSize);
var obx3 = "";
var obx5 = "";
while(results.next()){
var i=0
obx3 = results.getString(1);
logger.info('obx3 ' + obx3);
obx5 = results.getString(2);
logger.info('obx5 '+obx5);
while(i<resultSize)
{
createSegment('OBX', tmp,i);
tmp['OBX'][i]['OBX.1']['OBX.1.1'] = i;
tmp['OBX'][i]['OBX.3']['OBX.3.1'] = obx3;
tmp['OBX'][i]['OBX.5']['OBX.5.1'] = obx5;
i++;
}
}
dbConn.close();
Switched around the while statements, works now
while(i<resultSize){
var i=0
obx3 = results.getString(1);
logger.info('obx3 ' + obx3);
obx5 = results.getString(2);
logger.info('obx5 '+obx5);
while(results.next()){
createSegment('OBX', tmp,i);
tmp['OBX'][i]['OBX.1']['OBX.1.1'] = i;
tmp['OBX'][i]['OBX.3']['OBX.3.1'] = obx3;
tmp['OBX'][i]['OBX.5']['OBX.5.1'] = obx5;
i++;
}
}

Distinct with joins

How do I get distinct rows based on the Last_Name field when my format is as follows:
public ActionResult Index()
{
ResumeDbEntities srd = new ResumeDbEntities();
List<M_Employees> First_Name = srd.M_Employees.ToList();
List<M_Employees> Last_Name = srd.M_Employees.ToList();
List<M_Employees> CurrentLaborCategory = srd.M_Employees.ToList();
List<M_Offices> Location_Number = srd.M_Offices.ToList();
List<M_Offices> City = srd.M_Offices.ToList();
List<M_Offices> State = srd.M_Offices.ToList();
List<S_Emp_Resume> Resume_Name = srd.S_Emp_Resume.ToList();
var multipleTbl = (from p in Resume_Name
join t in Last_Name on p.Employee_Rec_Key equals t.Employee_Rec_Key
join o in Location_Number on t.Office_Rec_Key equals o.Office_Rec_Key
where t.Employee_Rec_Key == 3633
select new MultipleClassRes { M_Employeesdetails = t, S_Emp_Resumedetails = p, M_Officesdetails = o});
return View(multipleTbl);
}
Newly working with MVC but included the auto number from one of the joins.

How to improve query with two contexts - MVC5, LINQ n EF

I have two contexts. In one of them i have two views of which i get cods related to an entity from the another context. This query is taking too long time. How to improve it?
var negociacoes = _db.Negociacoes.Include(o=> o.User).ToArray();
var produtos = _oriDb.Vw_Produtos.ToArray();
var clientesVendedor = _oriDb.Vw_ClientesVendedores.ToArray();
var query = from n in negociacoes
join p in produtos on n.ProdutoId equals p.ProdutoId
join c in clientesVendedor on n.ClienteId equals c.codigo_entidade
select new NegociacaoView
{
NegociacaoId = n.NegociacaoId,
ProdutoId = n.ProdutoId,
Produto = p.descricao,
ClienteId = n.ClienteId,
Cliente = c.razao_social,
Rca = n.Rca,
Quantidade = n.Quantidade,
Preco = n.Preco,
Situacao = n.Situacao,
UserId = n.User.UserName,
Atendente = n.Atendente,
CondicaoId = n.CondicaoId,
DataCriacao = n.DataCriacao,
DataLiberacao = n.DataLiberacao,
Observacao = n.Observacao,
User = n.User
};
return query.ToList();
There are a couple of ways to speed this up:
It helps to run the smallest most efficient query first, then use those results to constrain the following queries.
Defining a select list so the database doesn't have to materialize every column will speed things up and use less memory.
Unfortunately, no matter how you do it in LINQ, you will end up with sql that uses large IN statements. A sproc would give you access to temp tables and joins that would be even better.
var negociacoes = _db.Negociacoes.Include(o=> o.User).ToArray();
//Use results of first query to constrain the second two. You could maybe combine the second two into one query.
var clientIds = negociacoes.Select(x => x.ClienteId);
var productIds = negociacoes.Select(x => x.ProdutoId);
var produtos = _oriDb.Vw_Produtos
.Where(x => productIds.Contains(x.ProdutoId))
//add a select. You're only using two columns from this table.
//.Select(x => new { })
.ToArray();
var clientesVendedor = _oriDb.Vw_ClientesVendedores
.Where(x => clientIds.Contains(x.codigo_entidade))
//add a select. You're only using two columns from this table.
//.Select(x => new { })
.ToArray();
var query = from n in negociacoes
join p in produtos on n.ProdutoId equals p.ProdutoId
join c in clientesVendedor on n.ClienteId equals c.codigo_entidade
select new NegociacaoView
{
NegociacaoId = n.NegociacaoId,
ProdutoId = n.ProdutoId,
Produto = p.descricao,
ClienteId = n.ClienteId,
Cliente = c.razao_social,
Rca = n.Rca,
Quantidade = n.Quantidade,
Preco = n.Preco,
Situacao = n.Situacao,
UserId = n.User.UserName,
Atendente = n.Atendente,
CondicaoId = n.CondicaoId,
DataCriacao = n.DataCriacao,
DataLiberacao = n.DataLiberacao,
Observacao = n.Observacao,
User = n.User
};
return query.ToList();

Using Parameters with Oracle Packages. ODP .NET

I have an Oracle function that returns a record set.
I introduced parameters to the Oracle function and this is causing the front-end code to go haywire.
Here's my front-end code.
OracleCommand od = oc.CreateCommand();
od.CommandType = System.Data.CommandType.Text;
od.CommandText = " select * from table(pkg_fetchPOInfo.getPORowsTable(:1,:2))";
//od.CommandText = "pkg_fetchPOInfo.getPORowsTable";
//od.CommandType = System.Data.CommandType.TableDirect;
OracleParameter op1 = new OracleParameter();
op1.ParameterName = "1";
op1.OracleDbType = OracleDbType.Varchar2;
op1.Direction = System.Data.ParameterDirection.Input;
op1.Size = 6;
op1.Value = strPONumber;
od.Parameters.Add(op1);
OracleParameter op2 = new OracleParameter();
op2.ParameterName = "2";
op2.OracleDbType = OracleDbType.Varchar2;
op2.Direction = System.Data.ParameterDirection.Input;
op2.Size = 3;
op2.Value = "US";
od.Parameters.Add(op2);
If I execute the query in the front-end SQLPLUS, I get a recordset.
This code works if I remove the parameters from the package and the front-end code.
select * from table(pkg_fetchPOInfo.getPORowsTable('1007446','US')); --works in SQLPLUS.
select * from table(pkg_fetchPOInfo.getPORowsTable()); --works in both places.
Am I assigning the parameters incorrectly?
Package Definition:
CREATE OR REPLACE
PACKAGE TESTP AS
function TESTPIPE(nr in number, nr2 in number) return varchartabletype pipelined;
END TESTP;
CREATE OR REPLACE
PACKAGE BODY TESTP AS
function TESTPIPE(nr in number, nr2 in number) return varchartabletype pipelined AS
CURSOR TESTPIPE_cur
IS
SELECT (level + 1) datam
FROM dual
connect by level < nr;
vtt varchartabletype ;
BEGIN
OPEN TESTPIPE_cur;
LOOP
FETCH testpipe_cur
BULK COLLECT INTO vtt LIMIT nr2;
FOR indx IN 1 .. vtt.COUNT
LOOP
Pipe Row ( vtt( indx ) ) ;
END LOOP;
EXIT WHEN testpipe_cur%NOTFOUND;
END LOOP;
END TESTPIPE;
END TESTP;
.NET Code:
public static void pipeTest()
{
String conString = GetConnectionString();
OracleConnection _conn = new OracleConnection(conString);
_conn.Open();
OracleCommand oCmd = new OracleCommand();
oCmd.CommandText = "begin open :crs for Select * from table(testp.testpipe(:nr,:nr2)); end;";
oCmd.CommandType = CommandType.Text ;
oCmd.Connection = _conn;
OracleParameter crs = new OracleParameter();
crs.OracleDbType = OracleDbType.RefCursor;
crs.Direction = ParameterDirection.Output;
crs.ParameterName = "crs";
oCmd.Parameters.Add(crs);
OracleParameter nr = new OracleParameter();
nr.OracleDbType = OracleDbType.Int64;
nr.Direction = ParameterDirection.Input ;
nr.ParameterName = "nr";
nr.Value = 25;
oCmd.Parameters.Add(nr);
OracleParameter nr2 = new OracleParameter();
nr2.OracleDbType = OracleDbType.Int64;
nr2.Direction = ParameterDirection.Input;
nr2.ParameterName = "nr2";
nr2.Value = 10;
oCmd.Parameters.Add(nr2);
using (OracleDataReader MyReader = oCmd.ExecuteReader())
{
int ColumnCount = MyReader.FieldCount;
// get the data and add the row
while (MyReader.Read())
{
String s = MyReader.GetOracleValue(0).ToString();
Console.WriteLine(string.Format("i={0}", s));
}
}
Console.ReadLine();
}