I want to join 2 tables and retrieve distinct rows based on 2 columns in entity framework.
I have read posts on web including SO.
In the code below,
1. I join 2 tables based on CurrentTurnID
key
2. I filter the table by the features that I want
3. I filter the table by setting conditions on selected features
4. I select a column to calculate the sum of all it's value
I need to retrieve records that have the same CurrentTurnID
just once. Here's my code:
int services = Convert.ToInt32(database.Tbl_CurrentTurn.AsNoTracking()
.Join(database.Tbl_pay.AsNoTracking(), f => f.CurrentTurnID,
s => s.CurrentTurnID, (f, s) => new
{
f.CurrentTurnOfficialID,
f.CurrentTurnID,
f.SickID,
f.Remove,
f.Payment,
f.ServicePayment,
s.isDeposit
})
.Where(w => w.SickID == SickId && w.Remove != true && w.Payment == true && w.isDeposit != true)
.Select(s => s.ServicePayment).DefaultIfEmpty(0).Sum());
If I add Distinct()
after Select()
statement, it would consider the ServicePayment
to filter distinct rows.
Update: The Image is attached to my Dropbox. The 2nd and the 3rd records have the same CurrentTurnID
value. So I want to consider just one of them. Then sum up records on ServicePayment
column. Please notice that other columns are different in these 2 records.
You can try a GroupJoin
to get that information without the need for Distinct
like this:
int services = Convert.ToInt32(database.Tbl_CurrentTurn.AsNoTracking()
.GroupJoin(database.Tbl_pay.AsNoTracking(), f => f.CurrentTurnID,
s => s.CurrentTurnID, (f, s) => new {f, s})
.SelectMany(x=> x.s.DefaultIfEmpty(), (f, s) => new
{
f.CurrentTurnOfficialID,
f.CurrentTurnID,
f.SickID,
f.Remove,
f.Payment,
ServicePayment = s != null ? s.ServicePayment : 0,
s.isDeposit
})
.Where(w => w.SickID == SickId && w.Remove != true && w.Payment == true
&& w.isDeposit != true)
.Select(x=> x.ServicePayment).Sum());
This may not compile correctly since I don't have all the variables and a small example I can use to test this.
You should be able to get this to work with very few changes. I use a similar query to get a list for a cost report.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.