I'm trying to update a specific record based off of a users selection. Regarding Entity Framework syntax, I'm not very familiar. Is it possible to achieve this SQL statement in Entity FrameWork?
Thank you!
update Table1
set Colum1='1'
where Column2='1234567'
var record = _db.Table1.where(r => r.Column2 == '1234567');
record.Column1 = '1'
_db.SaveChanges();
where _db is the Entity Framework DbContext class...
HTH.
Yes, Linq Version:
Table1Entity entity = from e in dbContext.Table1Entitys
where e.Column2 = '1234567'
select e
entity.Column1 = '1';
dbContext.SaveChanges();
And looks like Sunny has the Lambda version.
However, neither this nor Sunny's answer produces the exact SQL because they both actually produce a SELECT and an UPDATE:
SELECT <all columns>
FROM <table>
WHERE Column2 = '1234567'
UPDATE <table>
SET <allcolumns> = <allvalues>, etc etc
WHERE Column2 = '1234567'
If you want to just an UPDATE, then you would do something like:
var row = new Row();
// assuming a single column PK (id)
row.Column1 = '1';
row.Column2 = '1234567';
dbContext.Attach(row);
var entity = dbContext.Entity(entity);
entity.Property(e => e.Column2).IsModified = true;
dbContext.SaveChanges();
produces exactly:
UPDATE <Table>
SET Column2 = '1234567'
WHERE Column1 = '1'
// Note: ctx = your DbContext
var tbl1 = (from t in ctx.Table1 where t.Id == 1234567 select t).FirstOrDefault();
if (tbl1 != null) {
tbl1.Column1 = "1";
ctx.SaveChanges();
}
Related
I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();
Im working in a backend API using Java and MySql, and I'm trying to use #SqlResultSetMapping in JPA 2.1 for mapping a ONE-TO-MANY native query result into a POJO class, this is the native query:
#NamedNativeQuery(name = "User.getAll”, query = "SELECT DISTINCT t1.ID, t1.RELIGION_ID t1.gender,t1.NAME,t1.CITY_ID , t2.question_id, t2.answer_id FROM user_table t1 inner join user_answer_table t2 on t1.ID = t2.User_ID“,resultSetMapping="userMapping")
And, here is my result SQL mapping:
#SqlResultSetMapping(
name = "userMapping",
classes = {
#ConstructorResult(
targetClass = MiniUser.class,
columns = {
#ColumnResult(name = "id"),
#ColumnResult(name = "religion_id"),
#ColumnResult(name = "gender"),
#ColumnResult(name = "answers"),
#ColumnResult(name = "name"),
#ColumnResult(name = "city_id")
}
),
#ConstructorResult(
targetClass = MiniUserAnswer.class,
columns = {
#ColumnResult(name = "question_id"),
#ColumnResult(name = "answer_id")
}
)
})
And, here is the implementation of the POJO classes: (I just removed the constructor and the getters/setter)
MiniUser class
public class MiniUser {
String id;
String religionId;
Gender gender;
List<MiniUserAnswer> answers;
String name;
String city_id;
}
and the MiniUserAnswer class
public class MiniUserAnswer {
String questionId;
String answerId;
}
My goal is to execute this Query and return a list of MiniUser, and in each MiniUser: a list of his “answers", which is a list of MiniUserAnswer.
after running this code, I got this error:
The column result [answers] was not found in the results of the query.
I know why, it's because there is no “answers" field in the query select statement.
So, how can I accomplish something like this, considering the performance? This answers list may reach 100.
I really appreciate your help, Thanks in advance!
The query "SELECT DISTINCT t1.ID, t1.RELIGION_ID t1.gender, t1.NAME, t1.CITY_ID, t2.question_id, t2.answer_id" does not return a parameter called answers.
To obtain the result you are looking for I would use:
Option 1 (Criteria Builder)
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<UserTableEntity> cq = cb.createQuery(UserTableEntity.class);
Root<UserTableEntity> rootUserTable = cq.from(UserTableEntity.class);
Join<UserTableEntity,UserAnswerTableEntity> joinAnswerTable = rootUserTable.join(rootUserTable_.id) // if the relationship is defined as lazy, use "fetch" instead of "join"
//cq.where() NO WHERE CLAUSE
cq.select(rootUserTable)
entityManager.createQuery(cq).getResultList();
Option 2 (Named query, not native)
#NamedQuery(name = "User.getAll”, query = "SELECT t1 FROM UserTableEntityt1 join fetch t1.answers)
Option 3 (Entity subgraph, new in JPA 2.1)
In User Entity class:
#NamedEntityGraphs({
#NamedEntityGraph(name = "graph.User.Answers", attributeNodes = #NamedAttributeNode("answers"))
})
In DAO set hints in the entity manager:
EntityGraph graph = this.em.getEntityGraph("graph.User.Answers");
Map hints = new HashMap();
hints.put("javax.persistence.fetchgraph", graph);
I'm facing an issue to select the value from the same object. I provided the query below.
I'm migrating a Java J2EE application to Salesforce, the below query works in my SQL.
I'm trying to do the same in SOQL, but it doesn't work.
SELECT DATA1__c, TEXT__c
FROM PARAMETERS__c
WHERE ( (TYPE__c = 'ADMINISTRATEUR')
AND (KEY1__c LIKE 'MONTAGE%') (AND KEY2__c = ''))
AND (DATA1__c
IN (SELECT KEY1__c
FROM Parameters__c
WHERE TYPE__c = 'PERE_TECHNIQUE'))
In the above query I need to take the value where TYPE is based on 'TECHNIQUE' where KEY1__c should be matched to DATA1__c from the outer query.
The query is very similar to this example
SELECT Id
FROM Idea
WHERE ((Idea.Title LIKE 'Vacation%')
AND (CreatedDate > YESTERDAY)
AND (Id IN (SELECT ParentId
FROM Vote
WHERE CreatedById = '005x0000000sMgYAAU'))
The only difference is that IN clause is used with a different object.
In my query I'm trying to use IN clause from the same object parameters.
Kindly let me know in case of any further clarifications.
try the following
List<String> pereTechniqueParams = new List<String>();
for (String key:
[SELECT KEY1__c FROM Parameters__c WHERE TYPE__c = 'PERE_TECHNIQUE']) {
pereTechniqueParams.add(key.KEY1__c);
}
List<Parameters__c> params = [SELECT DATA1__c, TEXT__c
FROM PARAMETERS__c
WHERE (TYPE__c = 'ADMINISTRATEUR'
AND KEY1__c LIKE 'MONTAGE%'
AND KEY2__c = '')
AND DATA1__c IN:pereTechniqueParams];
UPDATE:
for (Parameters__c key1 : [SELECT KEY1__c
FROM Parameters__c WHERE TYPE__c = 'PERE_TECHNIQUE']) {
pereTechniqueParams.add(key1.KEY1__c);
}
Don't use String use Parameters__c
public class LookUpController {
public List<Parameters__c> getParamters() {
List<String> pereTechniqueParams = new List<String>();
for (Parameters__c key1 : [SELECT KEY1__c
FROM Parameters__c WHERE TYPE__c = 'PERE_TECHNIQUE']) {
pereTechniqueParams.add(key1.KEY1__c);
}
List<Parameters__c> params = [SELECT DATA1__c, TEXT__c
FROM PARAMETERS__c
WHERE TYPE__c = 'ADMINISTRATEUR'
AND KEY1__c LIKE 'MONTAGE%'
AND KEY2__c = ''
AND Data1__c IN: pereTechniqueParams];
return params;
}
}
The Vote Id and Idea Id is not same, The inner selection return list of Vote, And there is not result for sub-query Id IN (SELECT ParentId FROM Vote....
Channge Code To
set<Id> ideaIdSet = new set<Id>();
for(Vote vote : [SELECT ParentId FROM Vote WHERE CreatedById = '005x0000000sMgYAAU']){
ideaIdSet.add(vote.ParentId);
}
SELECT Id
FROM Idea
WHERE ((Title LIKE 'Vacation%')
AND (CreatedDate > YESTERDAY)
AND (Id IN ideaIdSet)
I am trying to get the max value from a table, doing something like this:
SELECT max(re.Sequence) FROM MyTable re WHERE re.ItemId = :itemId
So i can get for each itemId the maximum value for the column Sequence.
Tried with createQuery but didn´t worked:
string hql = #"SELECT new Int32(max(re.Sequence) FROM MyTable re WHERE re.Item.Id = :itemId";
List<Int32> lista = session
.CreateQuery(hql)
.SetParameter("itemId", idItem)
.List<Int32>()
.ToList();
Any help will be appreciated.
Best Regards.
Using the criteria syntax:
var criteria = session.CreateCriteria<MyTable>();
criteria.Add(Restrictions.Eq("ItemId", itemId));
criteria.SetProjection(Projections.Max("Sequence"));
var max = criteria.UniqueResult<int>();
Using the query over syntax:
var max = session.QueryOver<MyTable>().Where(x => x.ItemId.Equals(itemId)).Select(
Projections.Max<MyTable>(x => x.Sequence)).SingleOrDefault<int>();
We are trying to upgrade to NHibernate 3.0 and now i am having problem with the following Linq query. It returns "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS." error.
This is the linq query in the controller.
var list = (from item in ItemTasks.FindTabbedOrDefault(tab)
select new ItemSummary
{
Id = item.Id,
LastModifyDate = item.LastModifyDate,
Tags = (from tag in item.Tags
select new TagSummary
{
ItemsCount = tag.Items.Count,
Name = tag.Name
}).ToList(),
Title = item.Title
});
and the following is the sql generated for this query
select TOP ( 1 /* #p0 */ ) item0_.Id as col_0_0_,
item0_.LastModifyDate as col_1_0_,
(select (select cast(count(* ) as INT)
from dbo.ItemsToTags items3_,
dbo.Item item4_
where tag2_.Id = items3_.Tag_id
and items3_.Item_id = item4_.Id),
tag2_.Name
from dbo.ItemsToTags tags1_,
dbo.Tag tag2_
where item0_.Id = tags1_.Item_id
and tags1_.Tag_id = tag2_.Id) as col_2_0_,
item0_.Title as col_3_0_ from dbo.Item item0_ order by item0_.ItemPostDate desc
ps:If i remove the Tags property in the linq query, it works fine.
Where is the problem in the query?
Thanks in advance.
I've got the same Generic ADO Exception error, I think it's actually the limitation of SQL server;
Is it possible somehow load object graph with projections in collections?
If I try this one:
var cats = q.Select(t => new cat()
{
NickName = t.NickName,
Legs = t.Legs.Select(l => new Leg()
{
Color = l.Color,
Size = l.Size
}).ToList()
}).ToList();
That does the same error..