Linq query for not in operator - c#

I have a sql query. I need a linq query for that.
select rightname
from IB_Right_Master
where id not in (select RightID from IB_Group_Rights where GroupID = '3');
Table : RightMaster
ID | RightName | RightGroupName |
----------------------------------------------
1 | Test | Add Group Users |
2 | Add Group | Page Access rights |
3 | Page Access | Group deletion |
3 | Delete Group | Group deletion |
----------------------------------------------
Table : Group Rights
ID | RightID | GroupID | Status |
------------------------------------------------------------
1 | 1 | 1 | True |
2 | 1 | 2 | True |
3 | 2 | 3 | True |
4 | 3 | 4 | True |
5 | 1 | 3 | True |
------------------------------------------------------------

Try this
var data = (from m in db.IB_Right_Master
where m.Id != 1
select m.RightName).ToList();

You can try this
var result = from m in db.IB_Right_Master
where IB_Group_Rights.Any(r => r.RightID != 1 && r.RightID == m.Id)
select m.RightName

Try this
var lst = IB_Right_Master.Where(x => !IB_Group_Rights.Any(y => x.id==y.RightID && y.id==1))
.Select(x => x.rightname).ToList();

Related

Create a stored procedure to display rows with a connected column value from another column

I have this SQL Server database already stored
ID | TaxDecNo | OwnerName | PrevTaxDec
----------------------------------------------
1 | 5374 | John | 11135
2 | 9864 | Doe | 7394
3 | 11135 | John | 21784
4 | 7394 | Doe | 6872
5 | 21784 | John | NULL
6 | 6872 | Doe | NULL
When I'm going to display ID 3
ID | TaxDecNo | OwnerName | PrevTaxDec
----------------------------------------------
1 | 5374 | John | 11135
3 | 11135 | John | 21784
5 | 21784 | John | NULL
When I'm going to display RecordID 2
ID | TaxDecNo | OwnerName | PrevTaxDec
----------------------------------------------
2 | 9864 | Doe | 7394
4 | 7394 | Doe | 6872
6 | 6872 | Doe | NULL
The display only stop when no PrevTaxDec connects TaxDec No value.
I got this solution given to me a while but I don't know how to convert it to stored procedure which the data is already inserted the table
DECLARE #ID int = 3;
WITH YourTable AS(
SELECT V.ID,
V.TaxDecNo,
V.PrevTaxDec
FROM (VALUES(1,5374,11135), --This value must already inserted in the table
(2,9864,7394),
(3,11135,21784),
(4,7394,6872),
(5,21784,NULL), --I assume you aren't really mixing datatyoes. 'N/A' can't be inserted into an int column
(6,6872,NULL))V(ID,TaxDecNo,PrevTaxDec)),
--Solution
rCTEup AS(
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM YourTable YT
WHERE YT.ID = #ID
UNION ALL
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM rCTEup r
JOIN YourTable YT ON r.TaxDecNo = YT.PrevTaxDec),
rCTEdown AS(
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM YourTable YT
WHERE YT.ID = #ID
UNION ALL
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM rCTEdown r
JOIN YourTable YT ON r.PrevTaxDec = YT.TaxDecNo)
SELECT ID,
TaxDecNo,
PrevTaxDec
FROM rCTEup
UNION ALL
SELECT ID,
TaxDecNo,
PrevTaxDec
FROM rCTEdown
WHERE ID != #ID; --As it'll be in rCTEup

LINQ-to-Entities query on Entity Framework

I'm having a hard time creating a LINQ-to-Entities query that would fulfill my requirement.
I have two tables: Booking and ProcessStatusLog.
Booking table:
PNNumber (PK)
AccountName
ProcessStatusLog table:
ID (PK)
PNNumber (FK)
InsuranceCode
Status
UpdatedOn
Here is the sample data for these tables:
Booking table
| PNNumber | Account Name |
+----------+----------------+
| 11111 | Boston Celtics |
| 22222 | Miami Heat |
| 33333 | LA Lakers |
ProcessStatusLog table:
| ID | PNNumber | InsuranceCode | Status | UpdatedOn |
+------+-----------+---------------+--------------+-------------+
| 1 | 11111 | null | NEW | 02/22/2020 |
| 2 | 11111 | FIRE | FOR REVIEW | 02/23/2020 |
| 3 | 22222 | null | NEW | 02/24/2020 |
| 4 | 22222 | MORTGAGE | FOR REVIEW | 02/25/2020 |
| 5 | 22222 | MORTGAGE | CORRECTION | 02/26/2020 |
| 6 | 22222 | FIRE | FOR REVIEW | 02/27/2020 |
| 7 | 33333 | null | NEW | 02/28/2020 |
| 8 | 22222 | FIRE | APPROVED | 02/29/2020 |
Now, I want to get a list of bookings per latest status.
For example: if I want to filter the bookings where the latest status is "CORRECTION", I will get the booking with PNNumber 22222.
If searching for "FOR REVIEW", I will just get the booking with PNNumber 11111.
If searching for "NEW", I will just get the booking with PNNumber 33333.
How can I write the EF query for this?
Thanks.
context.ProcessStatusLog.where(x=>x.Status == "FOR REVIEW")
.OrderByDescending(x => x.UpdatedOn)
.Take(1);
You can use Join() to achieve it.
var result = context.ProcessStatusLog.Join(context.Booking, s => s.PNNumber, b => b.PNNumber, (s, b) => new { booking = b, StatusLog = s).Where(BookingAndStatusLog => BookingAndStatusLog.StatusLog.Status == your_parameter)
.OrderByDescending(BookingAndStatusLog => BookingAndStatusLog.StatusLog.UpdatedOn)
.Take(1);
Try below Query.
context.ProcessStatusLog.where(x=>x.Status == "FOR REVIEW")
.OrderByDescending(x => x.UpdatedOn)
.ToList();
So far my understanding of your question, you can try-
var result= context.ProcessStatusLog.OrderByDescending(x => x.UpdatedOn)
.FirstOrDefault(x=>x.Status == "CORRECTION");
OR
var result= context.ProcessStatusLog.where(x=>x.Status == "CORRECTION")
.OrderByDescending(x => x.UpdatedOn)
.FirstOrDefault();
it's return a single object of your ProcessStatusLog class.
using (var ctx = new SchoolDBEntities())
{
var student = ctx.Students
.SqlQuery("Select top1 from ProcessStatusLog where Status like '%"+#APPROVED+"%' order by UpdatedOn", new SqlParameter("#APPROVE", yourinputparameter))
.FirstOrDefault();
}

How to only select child entities of an entity in entity framework? [duplicate]

This question already has answers here:
Writing Recursive CTE using Entity Framework Fluent syntax or Inline syntax
(3 answers)
Closed 3 years ago.
I'd like to select only child below CFO and its subchild entities in an Entity Framework select statement.
Here's my table:
+-------+------------+----------+
| OrgId | Name | ParentId |
+-------+------------+----------+
| 1 | COO | |
+-------+------------+----------+
| 2 | CFO | |
+-------+------------+----------+
| 3 | Accountant | 2 |
+-------+------------+----------+
| 4 | Bookkeeper | 3 |
+-------+------------+----------+
| 5 | Controller | 2 |
+-------+------------+----------+
| 6 | Operations | 1 |
+-------+------------+----------+
I'd like to select only this:
+-------+------------+----------+
| OrgId | Name | ParentId |
+-------+------------+----------+
| 3 | Accountant | 2 |
+-------+------------+----------+
| 4 | Bookkeeper | 3 |
+-------+------------+----------+
| 5 | Controller | 2 |
+-------+------------+----------+
The entity framework select:
public virtual IList<OrgStructureModel> GetAll()
{
using (var db = _context)
{
var result = _session.GetObjectFromJson<IList<OrgStructureModel>>("OrgStructure");
if (result == null)
{
result = db.OrgStructures
.Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentId == org.OrgId).Count() > 0))
.ToList();
_session.SetObjectAsJson("OrgStructure", result);
}
return result;
}
}
How can this be achieved in EF?
Here's what I've tried
I've tried testing to just show child with any parent .Where(e => e.ParentId != null):
result = db.OrgStructures
.Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentId == org.OrgId).Count() > 0))
.Where(e => e.ParentId != null)
.ToList();
But this returned 0 results
Definition of ToOrgStructureModel:
public static OrgStructureModel ToOrgStructureModel(this OrgStructure org, bool hasChildren)
{
return new OrgStructureModel
{
OrgId = org.OrgId,
ParentId = org.ParentId,
Name = org.Name
hasChildren = hasChildren
};
}
Update:
It looks like something's wrong with the Telerik TreeList Control where the above query has data, but the control won't output the data. But the question remains, how do I get OrgId: 3,4,5 with LINQ?
Only bring back the results where the ParentId is not null.

Select values from one table based on specific value of another table Linq

I have 2 tables:
Location
id | user_id | latitude | longitude|
1 | 2 | 11.32323 | 11.32323 |
2 | 3 | 12.32323 | 12.32323 |
3 | 4 | 21.32323 | 12.32323 |
Task
id | user_id | status |
1 | 2 | 0 |
2 | 2 | 1 |
3 | 2 | 0 |
4 | 2 | 2 |
5 | 2 | 1 |
6 | 2 | 0 |
7 | 3 | 1 |
8 | 3 | 1 |
9 | 3 | 1 |
I want to select all rows from location table in which users have
either no record in Tasks table (for e.g. user_id = 4)
or if records
exists then all of them must have status equals to 1 (for e.g. user_id
= 3).
In above example, user_id = 2 should not be selected because it has rows in Tasks table with status other than 1.
I am not very much familiar with SQL and LINQ so any help would be appreciated.
This is the expected result:
Result
id | user_id | latitude | longitude|
2 | 3 | 12.32323 | 12.32323 |
3 | 4 | 21.32323 | 12.32323 |
Location with user_id = 2 was ignored because it has some rows in Tasks table with status other than 1.
Location with user_id = 3 was selected because all rows in Tasks table has status = 1.
Location with user_id = 4 was selected because there were no rows in Tasks table with user_id = 4.
Looking at you requirements could be this
select * from location
where user_id not in (select distinct user_id from task )
or user_id not in (select distinct user_id from task where status != 1);
Your conditions are equivalent to saying that no non-"1" value exists in task. I would write this as:
select l.*
from location l
where not exists (select 1 from tasks where t.user_id = l.user_id and t.status = 1);
I prefer not exists to not in because not in will filter out all rows if user_id is ever NULL in tasks.
Using a LEFT JOIN without a sub-SELECT:
SELECT
l.id,
l.user_id,
l.latitude,
l.longitude
FROM
Location l
LEFT JOIN Task t
ON l.user_id = t.user_id
WHERE
t.id IS NULL /* No record in tasks table */
OR (t.id IS NOT NULL AND l.status = 1) /* if records exists then all of them must have status equals to 1 */

LINQ join tables with value if no match

I know that there are some examples but I could not apply them on my code. I am pretty new to Linq and SQL. I have two tables I want to join.
First Table:
--------------
| Id | Count |
--------------
| 1 | 10 |
--------------
| 2 | 4 |
--------------
Second Table:
--------------
| Id | Name |
--------------
| 1 | Tom |
--------------
| 2 | John |
--------------
| 3 | Nick |
--------------
| 4 | Max |
--------------
As you can see, the second table has more records than the first. My goal is to join them based on the Id. The problem is that after I have joined the tables it only displays the matching records, which is Id 1 and 2. Though I want to display every Id (from 1 to 4) and if there is no match in both tables, there should be a default value 0.
It should look like this:
----------------------
| Id | Name | Count |
----------------------
| 1 | Tom | 10 |
----------------------
| 2 | John | 4 |
----------------------
| 3 | Nick | 0 |
----------------------
| 4 | Max | 0 |
----------------------
So far I have got this code:
// first table
var listCount = entity.tblKundes.Where(x => x.Studio == 2)
.Select(x => new { x.Id, x.Name})
.GroupBy(x => x.Name).ToList();
// second table
var listBerater = entity.tblUsers.Where(x => x.Studio == 2)
.Select(x => new { x.Id, x.Name})
.ToList();
// This join should be edited so that it displays non matching records as well
var test = listCount.Join(
listBerater,
count => count.Key,
berater => berater.Id,
(count, berater) => new { listCount = count, listBerater = berater }
).ToList();
Edit:
var test2 = (from list in listCount
join berater in listBerater on list.Berater equals berater.Id into gj
from sublist in gj.DefaultIfEmpty()
select new { sublist.Id, sublist.Nachname, sublist.Vorname }).ToList();
There is a typical concept in every Structured Query Languages which is called "Left join". Left-Join means that you will have all rows of data from first table even there is no equivalent in the second one. "Inner-Join" is a little different and only looks for matched rows of data.
Here you can find enough and complete information about your issue.
Left Join

Categories