LINQ statement equivalent to sum query in SQL [duplicate] - entity-framework

This question already has answers here:
How to force LINQ Sum() to return 0 while source collection is empty
(7 answers)
Closed 2 years ago.
I have SQL table with data::
UserId POINTS
121 5
122 6
121 4
122 3
121 1
To calculate the sum of the points for respective userid
SELECT SUM(POINTS) FROM TBL_SCORED_POINTS WHERE UserId = 121;
How can I convert this to LINQ Query?
public class ScoredPointModel
{
public int UserId { get; set; }
public int ScoredPoints { get; set; }
}
In LINQ query, I have to make where clause dynamic, I mean the where clause value will come from the user? How can I do this?

Is this the sort of thing you are looking for:
var total = ScoredPointModels.Where(spm => spm.UserId == userId).Sum(spm => spm.ScoredPoints);

Related

List has more than 1 row for assignment to SObject

I am getting error
List has more than 1 row for assignment to SObject
if I limit the query with one record it's working, but I wanted to get the list of records
public static List<Account> AccountsRequiringDebtCase()
{
Integer creditTermDate30 = 2;
Integer creditTermDate35 = 7;
Integer creditTermDate45 = 17;
List<Account> accList = new List<Account>();
if(Date.today().Day()==creditTermDate30){
accList.add([
select Id, Has_Open_Debt_Case__c, Most_Recent_Statement_Date__c
from Account where
Has_Open_Debt_Case__c = FALSE and
Day_60_Balance__c > 0 and Credit_Terms__c = 30 Limit 10
]);
}
List has more than 1 row for assignment to SObject
You should check document of Salesforec List Class
List.add() support only one element, that's why it error when query return more than one record. You have to use addAll to add list of record
accList.addAll(fromList)

Native query to Laravel eloquent

Good day, I have 3 tables which is products, users, and pivot product_user table.
and I want to fetch all the data in the main table if that row contains a pivot data.
Example
products table
ID Name
1 sample 1----------> is in pivot table **product_user**
2 sample 2----------> is in pivot table **product_user**
3 sample 3
users table
ID Name
1 user1-------------> is in the pivot table **product_user**
2 user2
3 user3-------------> is in the pivot table **product_user**
product_user
product_id user_id
1 1
3 2
In this scenario how can I fetch the data in the two main table that contains pivot data?
How can I achieve the result of this query in laravel way?
SELECT p.`name`, u.`first_name`
FROM product_user AS pu
LEFT JOIN products AS p
ON pu.`product_id` = p.id
LEFT JOIN `users` AS u
ON pu.`user_id` = u.`id`
result
name first_name
sample 1 user firstname
You have a BelongsToMany relationship Product ↔ User:
class ProductUser extends Model {
public function product() {
return $this->belongsTo(Product::class);
}
public function user() {
return $this->belongsTo(User::class);
}
}
$pivots = ProductUser::with('product', 'user')->get();
foreach($pivots as $pivot) {
// $pivot->user->first_name
// $pivot->product->name
}

C# Entityframework how to include based on condition

I have a table with one to many to many relation ie
ManyToMany table:
MenuGroup
menuid groupid
1 4
1 5
Menu
menuid name
1 One
2 Two
Group
groupid name
4 group4
5 group5
Groupuser
groupid userid
4 101
4 103
5 102
i would like to get all menus of the user 101
ie
Menuid groupid name
1 4 group4
But i am getting the wrong out put eventhough writing the correct join queries. Can anyone help what am i doing wrong here?
Menuid groupid name
1 4 group4
1 5 group5
(from m in context.Menus
join mg in context.MenuGroup on m.MenuId equals mg.MenuId
join gu in context.Groupuser on mg.GroupId equals gu.GroupId
where gu.UserId == 101
select m);
i would like to include only this particular user's group details though this menu is in other group as well.
my expected output in json would be
{
"menuid": 1,
"name": "One",
"groups":[
{
"groupid":4,
"name":"group4"
}
]
}
Your linq query looks good, I suspect data issue, but would you like to try the following query to see what you get back. This following query requires navigation properties declared.
var userMenus = context.GroupUser.Where(u=>u.UserId = 101).SelectMany(g=>g.Group.Menus
.Select(m=> new {Menu=m.MenuId, GroupId=g.GroupId,GroupName=g.Group.name))
.ToList();
In case you want the complete Menu object
var userMenus = context.GroupUser.Where(u=>u.UserId = 101).SelectMany(g=>g.Group.Menus
.Select(m=> new {Menu=m.Menu, GroupId=g.GroupId,GroupName=g.Group.name))
.ToList();
In case you don't care about Group columns and just want Menu then
var userMenus = context.GroupUsers.Where(u => u.UserId == 101)
.SelectMany(g => g.Group.Menus.Select(m=>m.Menu));

Compare the value of 2 rows in 1 query

I have a table structure is like this:
USERID int
LOGIN_DATE DateTime
LOGOUT_DATE DateTime
LOGIN_STATUS varchar(10)
The requirement is to retrieve the top 2 rows for a particular USERID sorted by LOGIN_DATE ASC. Then compare the 2 LOGIN_DATE records and check if they are less than 5 minutes.
Can this be done in a single LINQ statement?
Thanks
Parameswaran
Something like this should work (untested)
bool isRecentLogIn = db.Users
.OrderBy(u => u.LOGIN_DATE)
.Take(2)
.All(u => u.LOGIN_DATE.AddMinutes(5) < DateTime.Now);

How can I get data from two tables?

I am using Hibernate and PostgreSql. In hibernate I have two classes like:
Mobile(id, name, serial no,model_no)
Model(id, description, value)
Now Model class's values are stored in Mobile class (model_no). This Mobile class doesn't have any reference to Model class.
In Model class has data like:
Modal
======
id description value
1 aaaa 1
2 bbbbb 2
3 ccccc 3
4 ddddd 12
5 eeee 40
Here this value is being stored in Mobile table. In Mobile table I have model_no as 0 (which is not in Model, I don't want to put that value in Model table, because if I put I needs to change lot of code.
Now what I want a query to get the out put like
value description
---- ------------
0 UNKNOWN
1 aaaa
2 bbbbb
3 ccccc
4 ddddd
5 eeee.
like this. To get the all model_nos I can use a query like
select modal_no from Mobile
where modal_no in(select value from Modal) or model_no = 0
but here I what the description also which is in Model table. Can anybody help?
Thank u bro for your response, as i mentioned this Mobile table(Hibernate Mobile class) don't have reference to the Model table(in hibernate Model class). If i have reference to Model in Mobile class then your answer will be 100% correct. In my Mobile class this model_no is integer value. If i use your query in hql i will get the exception like "path expected". I want Hql(or sql) query to get the output with 0 value.
my hibernate Mobile class is like this
class Mobile {
int id;
int model_no; // this model_no has 0 + modal_no values(1,2,3,12,42).
// some references like
Manufacture manf;
SerialNo serialno;
Customer cust;
getters and setters
}
My Hibernate Model class is like ...
class Model{
int id;
String description;
int value; this column has 1,2,3,12,42. it don't have 0.
setters and getters.
}
A left join would accomplish that:
select Mobile.modal_no
, Modal.description
from Mobile
left join
Modal
on Mobile.model_no = Modal.value