Linq Group and Count in IEnumerable - asp.net-mvc

I have the following LINQ Query in my controller which queries my IEnumerable Collection, the grouping works when I output the results in my view but when I try and add a count on the column I have grouped it fails miserably. I was wondering if anyone could help at all, I have been looking at previous examples but I am missing something obvious.
Grouped //Working fine and returning grouped Descriptions
itemdetails = (from c in db.CLIENTDETAILS
join l in db.LOCATIONS on c.CLIENTNUMBER equals l.CLIENTNUMBER
where c.CLIENTNUMBER == clientNumber
join i in db.ITEMDETAILS on l.LOCNUMBER equals i.LOCNUMBER
where i.LOCNUMBER == l.LOCNUMBER
select i).GroupBy(it => it.DESC).Select(grp => grp.FirstOrDefault()).OrderBy(x => x.DESC)
What I have tried to get Group and Count in LINQ //Not working returning error
itemdetails = (from c in db.CLIENTDETAILS
join l in db.LOCATIONS on c.CLIENTNUMBER equals l.CLIENTNUMBER
where c.CLIENTNUMBER == clientNumber
join i in db.ITEMDETAILS on l.LOCNUMBER equals i.LOCNUMBER
where i.LOCNUMBER == l.LOCNUMBER
select i).GroupBy(it => it.DESC).Select(grp => new {DESC = grp.key, Count = grp.COUNT()}).OrderBy(x => x.DESC)
This give me the following error :-
cannot implicitly convert type system linq iorderedqueryable to system.collections.generic.ienumerable
Thanks for your help as always.

Your two queries are returning different data, the first is returning items of type ItemDetail, while the second query is returning items of an anonymous type.
If you want an IEnumerable of an anonymous type, you will need to declare it using the var keyword, i.e.
var itemdetails = (from c in db.CLIENTDETAILS
join l in db.LOCATIONS on c.CLIENTNUMBER equals l.CLIENTNUMBER
where c.CLIENTNUMBER == clientNumber
join i in db.ITEMDETAILS on l.LOCNUMBER equals i.LOCNUMBER
where i.LOCNUMBER == l.LOCNUMBER
select i).GroupBy(it => it.DESC).Select(grp => new {DESC = grp.key, Count = grp.COUNT()}).OrderBy(x => x.DESC)

Related

How can I get the content by the User Id when using GroupBy in Linq

//Used to get the data I wanted
var MatchResult = (from a in User
join b in UserResult on a.Id equals b.UserId
where a.Status == "Active" select new
{
a.Id,b.Win,b.Lost,b.WinRate
}
//Used to Append the info grouped By UserId
var result = MatchResult.GroupBy(x => x.UserId)
.Select(grp => new { UserId= grp.Key,
UserEmail = grp.Select(x => x.UserEmail ).FirstOrDefault(),
Content = MatchResult.Where(x => x.UserId== grp.Key).ToList() }).ToList();
As the picture shown below, Columns for content is getting a repetitive from userId 1 I try to use read the linq var result in order to sort out the content by Where clause. but turns out I am getting this error message
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.

LINQ to Entities returning NULL when searching by GUID

I have a LINQ to Entities Query that is suppose to return a specific resultset based on the GUID provided.
[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)]
public List<OrderDetails> GetOrderDetailsByGUID(Guid OrderID)
{
var listit =(from OV in EC.OrderProductVariants
join O in EC.Orders on OV.OrderId equals O.Id
join PV in EC.ProductVariants on OV.ProductVariantId equals PV.Id
join P in EC.Products on PV.ProductId equals P.Id
join CT in EC.Customers on O.CustomerId equals CT.Id
join AD in EC.Addresses on CT.BillingAddress_Id equals AD.Id
where O.OrderGuid == OrderID
select new OrderDetails
{
OrderID = O.OrderGuid,
Company = AD.Company,
ShippingMethod = O.ShippingMethod,
Product = P.Name,
QuantityOnOrder = OV.Quantity
}
).ToList();
return listit;
}
It Returns NULL, can anyone tell me what I am doing wrong?
All solution that could work in a scenario like this is to create a view and do just a one liner code to access it
var q = EC.OrderProductVariants.SingleOrDefault(u => u.OrderGuid.Equals(guid));

LINQ convert DateTime to string

List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();
The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?
Exception error:
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim
In other words, return the date itself and convert it to a string after it executes on SQL side:
(
select new { Username = u.Username,
PostingDate = c.Date
[...]
})
.ToList() // runs on SQL and returns to the application
.Select(o => // is not generating a SQL, it is running on the app
new Post { Username = o.Username,
PostingDate = o.PostingDate.ToString(),
[...]
})
You can remedy your problem by projecting into an anonymous type, and then at a later step project into Post after the data has already been returned from the DB.
(from ....
select new { /* stuff */, Date = c.Date })
.AsEnumerable()
.Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
.ToList();
However, given that you have a property called PostingDate, the original source being a date, I would recommend your revise your object to actually keep the value as a DateTime instead of a string.
I dont think this can be done in a direct way.
var list =
select new Post { Username = u.Username, PostingDate = SqlFunctions.StringConvert(c.Date), Data = c.Comment }
from
(from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending).AsEnumerable()
).ToList();
Also with EF4 you can try something like this:
List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = SqlFunctions.DateName(c.Date), Data = c.Comment }
).ToList();

EF 4.0 Linq to Enity query

Hi guys i need to replicate this SQL query in Linq to Entity
select * from Subscriber a
inner join User b on a.UserId = b.Id
where b.Username = 'Name'
May be some one may help.
Try this:
var query = from s in context.Subscribers.Include("User")
where s.User.Username == "Name"
select s;
This suppose that Subscriber has navigation property User referencing the user instance.
If you wan to use join (which is not needed) you can use this for inner join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id
where u.Username == "Name"
select new
{
Subscriber = s,
User = u
};
or this for left outer join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id into x
where u.Username == "Name"
from y in x.DefaultIfEmpty()
select new
{
Subscriber = s
User = y,
};

Linq to Entities compare DateTime in Sub Query

I'm trying to do this subquery:
var query =
from cjto in oContext.t_table_1
join cav in oContext.t_table_2 on cjto.cd_code equals cav.cd_code
where cav.dt_time >=
(from tu in oContext.t_table3
where tu.vl_code == "ABCD"
select tu.dt_check_time)
select cav;
However, I get the error:
Operator '>=' cannot be applied to operands of type 'System.DateTime' and 'System.Linq.IQueryable<System.DateTime?>'
How can I implement such query?
Tks
Ok, I got it... I needed to add the FirstOrDefault() so get the first element
var query =
from cjto in oContext.t_table_1
join cav in oContext.t_table_2 on cjto.cd_code equals cav.cd_code
where cav.dt_time >=
(from tu in oContext.t_table3
where tu.vl_code == "ABCD"
select tu.dt_check_time).FirstOrDefault()
select cav;
Tks

Resources