var query =
from u in this.Manager.GroupRecipients
join sz in this.Manager.Sub
on u.OD_ID equals sz.OD_Id into grpjoin
join z in this.Manager.Users
on u.ID equals z.ID
join m in this.Manager.Order_Details1
on u.OD_ID equals m.OD_Id
join o in this.Manager.Orders
on m.OrderId equals o.OrderId
join p in this.Manager.Products
on m.ProductId equals p.ProductId
from sz in grpjoin.DefaultIfEmpty()
where u.CampaignGroupId == groupid
select new DTO
{
FirstName = z.First_Name,
LastName = z.Last_Name,
Email = z.Email,
ProductName = p.Name,
PurchaseDate = (DateTime)o.OrderDate,
ExpiredDate = //stuck
};
I have this code and from the select clause, I can have a purchase date by using casting Datetime to the order date. However, I want to put expired date to be 1 year after purchasing. Is there any way to achieve the result? I was trying to put this code line
ExpiredDate = new DateTime(o.OrderDate).AddYears(1)
but an error saying that cannot convert from 'System.DateTime?' to 'long'
ExpiredDate = o.OrderDate.AddYears(1)
The original o.OrderDate will not be changed by this call, AddYears returns a new DateTime.
Your error is the result of calling a constructor that supposedly takes another DateTime object when no such constructor exists. You don't need a constructor call though, so just omit it.
I think the problem is DateTime() expects a long where you have given a another DateTime object. Check the different constructors of DateTime.
You can simply say
ExpiredDate = o.OrderDate.AddYears(1);
Related
We have two objects, Dates and ActiveEvents. Want to perform inner join on these with less than or equal to condition in linq. Same as ref of below SQL where consider #Tables are C# objects
Select A. from #Activities A
Inner Join #Dates D ON A.ActivityDate <= D.ProcessDate
Tried with below but it's not giving correct results.
var filteredActivity = (from e in ActiveEvents
from p in dates
where e.ActivityDate <= p.Date
select new ActiveEvent
{
ActivityDate = p.Date,
EventId = e.EventId
}).ToList();
And
var filteredActivity = (from e in ActiveEvents
from p in dates.Where(r => e.ActivityDate <= r)
select new ActiveEvent
{
ActivityDate = p.Date,
EventId = e.EventId
}).ToList();
Can you please suggest any better way to do this?
You can try this way
var filteredActivity = (from e in ActiveEvents
join p in dates
where e.ActivityDate <= p.ProcessDate
select new ActiveEvent
{
ActivityDate = p.Date,
EventId = e.EventId
}).ToList();
P/s: Ideally, between 2 tables should contain the foreign key to join like this join p in dates on e.Key equals p.ForeignKey
Based on your example, the query is filtering on ProcessDate but your linq query is filtering on p.Date. Are those the same field? The first example you gave should be correct.
How to convert this SQL in c# code
select t.Message
from [dbo].[tblA] t
inner join (
select Message, max(CreatedDate) as MaxDate
from [dbo].[tblA]
group by Message
) tm on t.Message = tm.Message and t.CreatedDate = tm.MaxDate
where Type='Enter'
Can you help me please .
I just created this ..but with inner join in more complicated for me.
var query = (from each in db.A
where each.StartDate == DateTime.Today
select each).FirstOrDefault();
If you want to get the whole message record in tblA with a max CreatedDate value, you can order the result and pick the first element, something like:
var query = from item in tblA
where item.Type = "Enter"
group item by item.Message into msgGroup
select msgGroup.OrderByDescending(t => t.CreatedDate).FirstOrDefault();
From what I understood, you want a message for which type is Enter and you want to get Max CreatedDate value for that message. If that's the requirement, i don't think you need inner join. You could use something like below in LINQ.
from m in tblA
where m.Type = "Enter"
group m by m.Message into temp
select new
{
Message = temp.Message,
CreatedDate = ( from temp2 in temp select temp.CreatedDate).max()
}
I've got a linq query extracting data from a table and I want to, being given a Date, convert it to week ( for example what week of the year it is ).
And the GetWeekofYear function:
private int GetWeekOfYear(DateTime d)
{
var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
return cal.GetWeekOfYear(new DateTime(d.Year, d.Month, 1), System.Globalization.CalendarWeekRule.FirstDay, System.DayOfWeek.Sunday);
}
In its current state, when I'm trying to test it ( using Postman / Fiddler ) I am getting the following error:
LINQ to Entities does not recognize the method 'Int32
GetWeekOfYear(System.DateTime)' method, and this method cannot be
translated into a store expression
The error occurs because Linq2Sql can not translate the GetWeekOfYear method to SQL.
Try the following:
select raw data instead into QuestionaireDetailsDTO
select new QuestionaireDetailsDTO() {
DepartureDate = transport.DepartureDate
};
add a getter to QuestionaireDetailsDTO that does the calculation:
public string Week => GetWeekOfYear(DepartureDate);
This way the conversion happens in memory instead of on the DB.
If the GetWeekOfYear method resides in a project that is not accessible by the consumer of the DTO, add a postprocessing step instead after you have selected the DTOs from the DB.
foreach (var result in query) {
result.Week = GetWeekOfYear(result.DepartureDate);
}
You can do this by using .AsEnumerable()
var query = from booking in context.BookingTables
join transport in context.TransportAllotments on booking.TransportAllotmentID equals transport.TransportAllotmentID
join passenger in context.Passengers on booking.BookingID equals passenger.BookingID
join result in context.QuestionaireResults on passenger.PassengerID equals result.PassengerID
join question in context.QuestionaireQuestions on result.QuestionaireQuestionID equals question.QuestionaireQuestionID
where transport.DepartureDate >= startDate && transport.DepartureDate <= endDate && booking.BookingID == id
.AsEnumerable()
select new QuestionaireDetailsDTO()
{
ID = booking.BookingID,
Date = transport.DepartureDate,
Question = question.QuestionText,
Week = GetWeekOfYear(transport.DepartureDate)
};
Hope it help.
As meintoined, this happents because LinqToSQL wasnt able to translate your method to SQL.
I think that answer from #GeorgPatscheider is not a best because you shouldn't change your data objects because some specific mechanisms of data access layer.
So, answer from #PhongDao is more cool, but him solution will download too many fields from database. You can change your code this way:
var query = from booking in context.BookingTables
join transport in context.TransportAllotments on booking.TransportAllotmentID equals transport.TransportAllotmentID
join passenger in context.Passengers on booking.BookingID equals passenger.BookingID
join result in context.QuestionaireResults on passenger.PassengerID equals result.PassengerID
join question in context.QuestionaireQuestions on result.QuestionaireQuestionID equals question.QuestionaireQuestionID
where transport.DepartureDate >= startDate && transport.DepartureDate <= endDate && booking.BookingID == id
// select only fields which we need
select new
{
ID = booking.BookingID,
Date = transport.DepartureDate,
Question = question.QuestionText,
DepartureDate = transport.DepartureDate
}
// retrieve data from DB
.ToArray()
// create items which you need
.Select(x=>
new QuestionaireDetailsDTO()
{
ID = x.ID,
Date = x.Date,
Question = x.Question,
Week = GetWeekOfYear(x.DepartureDate)
})
// forming results
.ToArray();
I am working on a WinForms project which requires to use Linq-To-Sql. I have been able to create my DataContext using the SqlMetal tool, and make some queries. But right now I have a problem that I havent been able to solve.
I am trying to make a LEFT OUTER JOIN as following:
MyDatabase db = new MyDatabase(...);
var query = from p in db.ParentTable
join t in db.ChildTable on new {A = p.child_ID, B = p.OtherID}
equals new {A = t.ID, B = t.OtherID} into j1
from c in j1.DefaultIfEmpty()
select new
{
...
};
When I write this query an error is raised at compile-time in the join word:
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'
I know this error is caused by the comparison between p.child_ID and t.ID since p.child_ID is int? and t.ID is int. But, How can I solve this? How can I perform the LEFT OUTER JOIN without having this error??
p.child_ID is int? since this column is marked as IS NULL in SQL.
Hope someone can help me, thanks in advance.
You can use GetValueOrDefault() method. It retrieves the value of the current Nullable object, or the object's default value.
In terms of your example :
var query = from p in db.ParentTable
join t in db.ChildTable on new {A = p.child_ID.GetValueOrDefault(0), B = p.OtherID}
equals new {A = t.ID, B = t.OtherID} into j1
from c in j1.DefaultIfEmpty()
select new
{
...
};
If the p.child_ID become null than it will return 0. Hope this will help !!
The first problem was that the property names should be the same as said casperOne♦, but the second problem is that you're comparing a nullable-int, p.child_ID, with a non-nullable-int, t.ID. So you could use the null-coalescing operator in this way:
(int)(p.child_ID ?? default(int))
In this case returns p.child_ID if it isn't null else returns default(int), that is 0.
The query will be:
var query = from p in db.ParentTable
join t in db.ChildTable on new {A = (int)(p.child_ID ?? default(T)), B = p.OtherID}
equals new {A = t.ID, B = t.OtherID} into j1
from c in j1.DefaultIfEmpty()
select new
{
//...
};
I need help on the LINQ query below, the join on multiple fields seems to work, but i get
"Invalid 'join' condition. An entity member is invoking an invalid
property or method."
I've already tried to swap the conditions on the join to no luck
(from o in orderSet
join opr in OrderProductSet on o.Id equals opr.OrderId.Id
join pri in ProductPricingSet on
new {BusinessUnitId = o.BusinessUnitId.Id, AccountId = o.Accountid.Id, ProductNameId = opr.ProductNameId.Id} equals
new {BusinessUnitId = pri.BusinessUnitId.Id, AccountId = pri.AccountId.Id, ProductNameId = pri.ProductId.Id}
where o.name.Equals("OE-000701")
select new {
o.name,
o.orderId,
opr.ProductNameId.Name,
opr.Quantity,
pri.Discount,
pri.FinalPrice
})