Like operator in LINQ to MYSQL - mysql

how to use like in linq for mysql. please see my code below. the parameter productname is giving the input value. but when i run this query, result is not coming. how to do this with mysql provider
public List<Product> GetProductsByProductName(string storeId, string productName)
{
Authenticate();
int _storeId = Convert.ToInt32(storeId);
var _products = (from p in context.products.AsEnumerable()
where p.StoreId == _storeId && p.ProductName.Contains(productName) && p.ProductIsAvailable.Equals(true)
orderby p.ProductName
select
new Product()
{
ProductName = p.ProductName,
CategoryID = p.CategoryId,
QuantityPerUnit = p.ProductUnit,
UnitPrice = p.ProductPrice,
DiscountValue = p.DiscountValue,
DiscountType = p.DiscountType,
ProductDescription = p.ProductDescription,
ProductURL = p.ProductURL,
ProductSmallDescription = p.ProductSmallDescription,
ProductListPrice = p.ProductListPrice
}).ToList();
}

here it is.... if it is MySQL we need to use .ToLower(). please see the code below.
p.ProductName.ToLower().Contains(productName.ToLower())
thank you...

Related

I don't know how to convert sql query to criteriabuilder in hibernate?

I need an total budget value. I can getting the answer from sql query but the problem is how to convert sql query to criteriaBuilder in hibernate.Here below the sql query:
SELECT SUM(ab.daily_budget) as todayBudgetTar FROM api_budget ab INNER JOIN api_ad_groups ad on ad.ad_group_id= ab.adgroup_id INNER JOIN api_campaigns c on c.campaign_id =ad.campaign_id INNER JOIN api_user_account ac on ac.user_id=ad.user_id WHERE ad.user_id = 234 AND ad.status=0 AND c.status=1 GROUP by "todayBudgetTar"
If someone knows plz help me.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
Root<ApiBudget> budget = query.from(ApiBudget.class);
Root<ApiAdGroups> adGroups = query.from(ApiAdGroups.class);
Root<ApiCampaigns> campaigns = query.from(ApiCampaigns.class);
Root<ApiUserAccount> userAccount = query.from(ApiUserAccount.class);
//this one is on your entity field name
query.select(criteriaBuilder.sum(budget.get("dailyBudget"));
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(
qb.equal(adGroups.get("adGroupId"), budget.get("adGroupId")));
predicates.add(
qb.equal(campaigns.get("campaignId "), adGroups.get("campaignId")));
predicates.add(
qb.equal(userAccount.get("userId"), adGroups.get("userId")));
predicates.add(
qb.equal(adGroups.get("userId"), 234));
predicates.add(
qb.equal(adGroups.get("status"), 0));
predicates.add(
qb.equal(campaigns.get("status"), 1));
query.where(predicates.toArray(new Predicate[]{}));
query.groupBy(budget.get("dailyBudget"));
TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
List<Object[]> resultList = typedQuery.getResultList();
Hi, i think this should work
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery(Object.class);
Root<Budget> budget = query.from(Budget.class);
Join adsetJoin = budget.join("adsetId");
Join campaignJoin = adsetJoin.join("campaign");
query.multiselect(builder.sum(budget.get("dailyBudget")));
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.equal(adsetJoin.get("status"), 0));
predicates.add(builder.equal(adsetJoin.get("userId"), userId));
predicates.add(builder.equal(campaignJoin.get("campaignStatus"), CAMPAIGNSTATUS.RUNNING));
if ((dashboardRequest.getStartDate() != null) && (dashboardRequest.getEndDate() != null)) {
Date fromDate = new Date(dashboardRequest.getStartDate());
Date toDate = new Date(dashboardRequest.getEndDate());
predicates.add(builder.between(adsetJoin.get("createdDate"), fromDate, toDate));
}
if (!predicates.isEmpty()) {
Predicate[] pr = new Predicate[predicates.size()];
pr = predicates.toArray(pr);
query.where(pr);
}
query.groupBy(budget.get("dailyBudget"));
List<Object> resultList = session.createQuery(query).getResultList();
List<Long> resultList2=resultList.stream().map(v ->((Number)v).longValue()).collect(Collectors.toList());
return resultList2;

Convert complex nested selects in Entity Framework query

I need to create a table in View by this View Model:
public class ApplicationContentViewModel
{
public BPMSPARS.Models.MySql.application application {get; set;}
public BPMSPARS.Models.MySql.content content { get; set; }
public BPMSPARS.Models.MySql.app_delegation app_delegation { get; set; }
}
But the query for creating new Table is very complex.
I use this query in MySQL, and I can get correct results by using it.
SELECT APP_UID, (SELECT CON_VALUE FROM content WHERE CON_CATEGORY = 'PRO_TITLE' AND CON_ID =
(SELECT PRO_UID from app_delegation WHERE del_thread_status='open' and USR_UID = '00000000000000000000000000000001' AND APP_UID = '9134216305aaaea1b67c4e2096663219')) AS TASK_NAME,
(SELECT CON_VALUE FROM content WHERE CON_CATEGORY = 'TAS_TITLE' AND CON_ID =
(SELECT TAS_UID from app_delegation WHERE del_thread_status='open' and USR_UID = '00000000000000000000000000000001' AND APP_UID = '9134216305aaaea1b67c4e2096663219')) AS PROCESS_NAME FROM app_delegation
WHERE del_thread_status='open' and USR_UID = '00000000000000000000000000000001' AND APP_UID = '9134216305aaaea1b67c4e2096663219'
But, I have to convert this query in linq or EF in MVC.
How Can I write This Query in Entity Framework query?
And How Can I display results in View?
Your SQL query seems (very) peculiar to me, as it is quite redundant. I am going to assume the sub-queries return a single value and enforce it with LINQ.
First I pulled out the common sub-query over app_delegation:
var USR_APP_Delegation = from a in app_delegation
where a.del_thread_status == "open" &&
a.USR_UID == "00000000000000000000000000000001" &&
a.APP_UID == "9134216305aaaea1b67c4e2096663219"
select a;
In LINQ it is easy to combine the two UID queries into one query:
var UIDs = (from a in USR_APP_Delegation
select new { a.PRO_UID, a.TAS_UID })
.Single();
Now you can do the name subqueries:
var TASK_NAME = (from c in content
where c.CON_CATEGORY == "PRO_TITLE" &&
c.CON_ID == UIDs.PRO_UID
select c.CON_VALUE)
.Single();
var PROCESS_NAME = (from c in content
where c.CON_CATEGORY == "TAS_TITLE" &&
c.CON_ID == UIDs.TAS_UID
select c.CON_VALUE)
.Single();
Then you can put all the queries together for the final result:
var ans = (from a in USR_APP_Delegation
select new {
a.APP_UID,
TASK_NAME,
PROCESS_NAME
})
.Single();
Again, this makes it obvious that your e.g. returning APP_UID when you know exactly what it is, and you are combining TASK_NAME and PROCESS_NAME into a query for no real advantage.
I would suggest using join against content makes a much more understandable query (even in SQL) and makes it clearer what is being returned:
var names = from a in app_delegation
join cpro in content on new { CON_ID = a.PRO_UID, CON_CATEGORY = "PRO_TITLE" } equals new { cpro.CON_ID, cpro.CON_CATEGORY }
join ctas in content on new { CON_ID = a.PRO_UID, CON_CATEGORY = "TAS_TITLE" } equals new { ctas.CON_ID, ctas.CON_CATEGORY }
where a.del_thread_status == "open" &&
a.USR_UID == "00000000000000000000000000000001" &&
a.APP_UID == "9134216305aaaea1b67c4e2096663219"
select new {
a.APP_UID,
Task_Name = ctas.CON_VALUE,
Process_Name = cpro.CON_VALUE
};

How Do I use Having and group By clause in hibernate?

I have a sql Query which is something like this.
SELECT VERSION_ID FROM VIEWTEST
where ( item_id='I001' and value ='V001')
or ( item_id='I002' and value ='V002')
or ( item_id= 'I003'and value ='V003')
group by VERSION_ID
having count(1) = 3
My ViewTest entity is something like this.
#Column(name = "version_id")
private String versionId;
#Column(name = "item_id")
private String itemId;
#Column(name = "value")
private String value;
Here is the Crieteria Query written by me.
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<String> query = criteriaBuilder.createQuery(String.class);
Root<ViewTest> testRoot = query.from(ViewTest.class);
List<Predicate> predicates = new ArrayList<Predicate>();
Predicate p1 = criteriaBuilder.equal(testRoot.get("itemId"), "I001");
Predicate p2 = criteriaBuilder.equal(testRoot.get("itemId"), "I002");
Predicate p3 = criteriaBuilder.equal(testRoot.get("itemId"), "I003");
Predicate v1 = criteriaBuilder.equal(testRoot.get("value"), "V001");
Predicate v2 = criteriaBuilder.equal(testRoot.get("value"), "V002");
Predicate v3 = criteriaBuilder.equal(testRoot.get("value"), "V003");
predicates.add(criteriaBuilder.and(p1 , v1));
predicates.add(criteriaBuilder.and(p2 , v2));
predicates.add(criteriaBuilder.and(p3 , v3));
Now I dont know how to add group By and Having clause to this criteria.
Can someone please help me out?
Found a better way to do it.
just added below to my code.
query.groupBy(testRoot.<String> get("versionId"));
query.having(criteriaBuilder.in(criteriaBuilder.count(testRoot.get("versionId"))).value(
queryCount));
this did the trick.
Have you looked at Projections?
Hibernate developer guide: Projections
Example:
List results = session.createCriteria(Cat.class)
.setProjection( Projections.projectionList()
.add( Projections.rowCount() )
.add( Projections.avg("weight") )
.add( Projections.max("weight") )
.add( Projections.groupProperty("color") )
)
.list();

HQL: Subquery returns more than 1 row

I'm new to HQL and I need help on this error.
QUERY:
String hqlsearchSelect =
"select new com.eteligent.core.loans.paging.LoansAppCustomerPageItem("
+ "main.loanno, (SELECT acct.id.clientid FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno), (SELECT acct.name FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno), main.acctsts, "
+ "main.loanbal, (SELECT acct.matdt FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno) )";
I think the query can't identify which record is it going to return.
CONSTRUCTOR(LoansAppCustomerPageItem):
public LoansAppCustomerPageItem( final String acctNo, final String cifNo, final String customerName, final Integer acctStat, final BigDecimal acctBal, final Date acctDueDate )
{
super();
this.acctNo = acctNo;
this.cifNo = cifNo;
this.customerName = customerName;
this.acctStat = acctStat;
this.acctBal = acctBal;
this.acctDueDate = acctDueDate;
}
If you wanna just one row from subquery use LIMIT 1 at the end of subquery.

LINQ-to-SQL load keyword from variable

public IQueryable<ArticleDisplay> SearchNumberOfArticles(int articleNr, string order)
var result = (
from category in db.ArticleCategories
join article in db.Articles on category.CategoryID equals article.CategoryID
orderby article.Date order
select new ArticleDisplay
{
CategoryID = category.CategoryID,
CategoryTitle = category.Title,
ArticleID = article.ArticleID,
ArticleTitle = article.Title,
ArticleDate = article.Date,
ArticleContent = article.Content
}
).Take(articleNr);
In PHP this would work, but in C# it doesn't. So, how to load keyword from variable and "print" it inside query? Here is order suppose to be replaced with descending or ascending.
Thanks
You can use an if statement
IQueryable<ArticleDisplay> SearchNumberOfArticles(int articleNr, string order)
{
................
var articles = from category in db.ArticleCategories
join article in db.Articles
on category.CategoryID equals article.CategoryID
select article;
if (string.IsNullOrEmpty(order) || order == "ascending" || order = "asc")
{
articles = articles.OrderBy(a => a.Date).Take(articleNr);
}
else
{
articles = articles.OrderByDescending(a => a.Date).Take(articleNr);
}
.............
}