IBookingRepository bookingResp = new BookingRepository();
IQueryable<bookingTest> bookings = bookingResp.GetAllBookingsByView();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = from booking in bookings
join f in getallAttendees on booking.UserID equals f.UserID into fg
from fgi in fg.DefaultIfEmpty() //Where(f => f.EventID == booking.EventID)
where
booking.EventID == id
select new
{
EventID = booking.EventID,
UserID = booking.UserID,
TrackName = booking.Name,
BookingStatus = booking.StatusID,
AttendeeName = booking.FirstName,
// name = account.FirstName,
AmountPaid = booking.Cost,
AttendeeAddress = booking.DeliveryAdd1,
City = booking.DeliveryCity,
Postcode = booking.Postcode,
Date = booking.DateAdded,
hel = fgi == null ? null : fgi.HelmetsPurchased }// Product table
Hi, the above query doesnt executes it gives an error: The specified LINQ expression contains references to queries that are associated with different contexts. Any one can spot the what the problem is with the query.
I think that your getAllAttendees is from a different context than bookings so you won't be able to join them. To give a more exact answer you need to show where bookings and getAllAttendees comes from.
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();
I need to be able to write the following query as a Criteria.
SELECT hist.*
FROM
Administration admin
INNER JOIN Item item ON item.AdministrationId = admin.AdministrationId
INNER JOIN ItemHistory hist ON hist.ItemId = item.ItemId
WHERE
item.itemId = #param
and hist.IsError =
(
SELECT (CASE status.errorType
WHEN 'Warning' THEN 0
ELSE 1
END
)
FROM
AdminStatus status
WHERE
status.AdministrationId = admin.AdministrationId
AND status.Group = 'Issues'
)
I'm pretty sure I'll need to do the sub query as a detached criteria:
var status = DetachedCriteria.For<AdminStatus>("status");
status.CreateAlias("status.Administration", "admin");
status.Add(Restrictions.Eq("status.Group", "Issues"));
status.SetProjection(Projections.Property("AdministrationId"));
status.SetProjection(Projections.Conditional(
Restrictions.Eq("status.errorType", "Warning"),
Projections.Constant(0),
Projections.Constant(1)));
But I'm not sure how to join that with my primary criteria:
var criteria = Session.CreateCriteria<ItemHIstory>("hist");
criteria.CreateAlias("ItemHistory.Item", "item");
criteria.CreateAlias("item.Administration", "admin");
But I'm not sure how to join that with my primary criteria:
Methods from Subqueries class glue detached sub-query with main criteria. Subqueries.PropertyEq in you case:
var criteria = Session.CreateCriteria<ItemHIstory>("hist");
criteria.CreateAlias("ItemHistory.Item", "item");
criteria.CreateAlias("item.Administration", "admin");
criteria.Add(Subqueries.PropertyEq("hist.IsError ", status))
And regarding detached criteria. Alias creation seems unnecessary:
var status = DetachedCriteria.For<AdminStatus>("status");
status.Add(Restrictions.EqProperty("status.AdministrationId", "admin.AdministrationId"));
status.Add(Restrictions.Eq("status.Group", "Issues"));
status.SetProjection(Projections.Conditional(
Restrictions.Eq("status.errorType", "Warning"),
Projections.Constant(0),
Projections.Constant(1)));
There are two tables, school and term. The school record must be shown, but the term record may not yet exist, therefore, the term may be null (thus the left join). The left joined table must be filtered by date for the current term if it exists. Can this be done in LINQ?
select school.school_name, term.term_start, term.term_end
from school
left join term on school.school_id = term.school_id and term.term_start <= '2017-10-21' and term.term_end >= '2017-10-21'
where school.active = 1
order by school.school_name
UPDATE:
After some input I have a left join but if a school is missing a term I still cannot make the start and end dates show as null - the school doesn't show at all if I am missing a term, and I want the school to show in the first column. What am I missing?? Here is the latest LinqPad code.
var query = ((from sc in Schools.Where(s => s.Active == 1 )
join t in Terms on sc.School_id equals t.School_id into ts
from tsub in ts.DefaultIfEmpty()
select new {name = sc.School_name,
start = tsub.Term_start,
end = tsub.Term_end})
.Where (o => o.start <= DateTime.Now && o.end >= DateTime.Now))
.OrderBy( o => o.name);
query.Dump();
UPDATE #2
Here is a screen shot of the SQL result, and I am trying to achieve the same thing in LINQ:
var query = from sc in school.Where(s = > s.active == 1 )
join t in term on sc.school_id == t.school_id
select new {name = sc.school_name,
start = t.term_start,
end = term.term_end}
.Where (o => o.start <= '2017-10-21' && o.end >= '2017-10-21')
.OrderBy( o => o.school_name)
I finally figured it out. If you put the .Where() clause on the joined table you will get null values if there is no matching record. Here is the LinqPad LINQ statement that works and it runs perfectly in .NET MVC.
var query = ((from sc in Schools.Where(s => s.Active == 1 )
join t in Terms.Where(x => x.Term_start <= DateTime.Now && x.Term_end >= DateTime.Now) on sc.School_id equals t.School_id into ts
from tsub in ts.DefaultIfEmpty()
select new {name = sc.School_name,
start = tsub.Term_start,
end = tsub.Term_end})
.OrderBy( o => o.name));
query.Dump();
How do i change the training events into a left outer join in training events im very basic at linq so excuse my ignorance its not retrieve records that don't have any trainnevent reference attached to it
var q = from need in pamsEntities.EmployeeLearningNeeds
join Employee e in pamsEntities.Employees on need.EmployeeId equals e.emp_no
join tevent in pamsEntities.TrainingEvents on need.TrainingEventId equals tevent.RecordId
where need.EmployeeId == employeeId
where need.TargetDate >= startdate
where need.TargetDate <= enddate
orderby need.TargetDat
It's best to use where in combination with DefaultIfEmpty.
See here: LEFT JOIN in LINQ to entities?
var query2 = (
from users in Repo.T_Benutzer
from mappings in Repo.T_Benutzer_Benutzergruppen.Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
from groups in Repo.T_Benutzergruppen.Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
//where users.BE_Name.Contains(keyword)
// //|| mappings.BEBG_BE.Equals(666)
//|| mappings.BEBG_BE == 666
//|| groups.Name.Contains(keyword)
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
var xy = (query2).ToList();
Which is equivalent to this select statement:
SELECT
T_Benutzer.BE_User
,T_Benutzer_Benutzergruppen.BEBG_BE
-- etc.
FROM T_Benutzer
LEFT JOIN T_Benutzer_Benutzergruppen
ON T_Benutzer_Benutzergruppen.BEBG_BE = T_Benutzer.BE_ID
LEFT JOIN T_Benutzergruppen
ON T_Benutzergruppen.ID = T_Benutzer_Benutzergruppen.BEBG_BG
var q = (from Labels in dc.tblArtworkDataLabels select Labels).ToList();
But I need this to do the quivalent of:
SELECT d.ID, d.labelID, d.dataID, d.data, l.templateID
FROM tblArtworkDataLabels AS d INNER JOIN
tblArtworkData AS l ON d.dataID = l.ID
WHERE (l.templateID = 238)
How do I do this in LINQ?
Edit
Sorry! Missed the WHERE clause on original statmenet!
var result = dc.tblArtworkDataLabels
.Join(dc.tblArtworkData, l => l.ID, d => d.dataID, (l, d) => new {l, d})
.Select(o => new {
Id = o.d.ID,
LabelId = o.d.labelID,
DataId = o.d.dataID,
Data = o.d.data,
TemplateId = o.l.templateID,
})
.Where(o => o.l.templateID == 238);
If you have a correct foreign key on tblArtworkData to the primary key on the tblArtworkDataLabels and have imported them correctly into the DBML designer you can have LINQ2SQL implicitly creating the join:
from l in tblArtworkData
where l.templateID = 238
select new {
Id = l.tblArtworkDataLabel.ID,
LabelId = l.tblArtworkDataLabel.labelID,
DataId = l.tblArtworkDataLabel.dataID,
Data = l.tblArtworkDataLabel.data,
TemplateId = l.templateID,
}
See my answer on the question "LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?" for how the implicit join translates to SQL.
Edit:
In the case I misunderstood your relations and you have many tblArtworkDataLabels to one tblArtworkData you have to turn the query the other way around
from d in tblArtworkDataLabels
where d.tblArtworkData.templateID = 238
select new {
Id = d.ID,
LabelId = d.labelID,
DataId = d.dataID,
Data = d.data,
TemplateId = d.tblArtworkData.templateID,
}
try
var q = (from Labels in dc.tblArtworkDataLabels
join data in dc.tblArtworkData on Labels.ID equals data.DataID select Labels).ToList();