Return List from Query - c#

I'm trying to return a list from a join query and having difficulty with the errors..
here is my code:
public IList<UniStock.Domain.Tables.Inventory> SelectInventoryListByColourSizeGroup(string styleColour, string sizeGroup)
{
var db = new UniStockContext();
IQueryable<Domain.Tables.Inventory> q = (from c in db.Inventories
join o in db.SizeGroupSizes
on c.Size.Trim() equals o.Description.Trim()
where (c.SytleColour == styleColour)
&& (o.SizeGroup.Description == sizeGroup)
select new
{
c
});
return q;
}
Error I'm seeing now is:
Cannot implicitly convert type 'System.Linq.IQueryable' to System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)`

The problem is, as the error says, you cannot return an anonymous type when your method is expecting a specific type. By using the new {} syntax you are creating an anonymous type. Simply remove new {}
public IList<UniStock.Domain.Tables.Inventory> SelectInventoryListByColourSizeGroup(string styleColour, string sizeGroup)
{
var db = new UniStockContext();
IQueryable<Domain.Tables.Inventory> q = (from c in db.Inventories
join o in db.SizeGroupSizes
on c.Size.Trim() equals o.Description.Trim()
where (c.SytleColour == styleColour)
&& (o.SizeGroup.Description == sizeGroup)
select c);
return q.ToList();
}

This part of your LINQ expression
select new { c } ;
Will give you a list of annonymous type objects. Your method signature says it should return an IList<Inventory>. Since you are not returning the expected type, you are getting this compile time error.
You select should be just c which is an alias for db.Inventories ( with the filter though)
var q = from c in db.Inventories
join o in db.SizeGroupSizes
on c.Size.Trim() equals o.Description.Trim()
where (c.SytleColour == styleColour)
&& (o.SizeGroup.Description == sizeGroup)
select c;
return q.ToList();
The variable q will be IQueryable<Inventory> and when you call the ToList() it will execute the LINQ expression and will get a List<Inventory> and you are returning that, which is matching with your method signature (IList<Signature>)

You are projecting into a new AnonymousType by doing this:
select new { c }
What you probably want is to select the object itself like this:
select c
Then you will want to append a .ToList() to the end to execute the query and populate the list.

Related

Have a Query want it in LINQ(Inner Join)

I'm having problem translating a query to LINQ in C# this is my query
select PDF.Name,PDF.Name
from PDF inner join PC
on PDF.Id=PC.Ref_PDF
having pc.Ref_Customer=_id
you should know that _id is something that i send to my method so I can find something with it
so far I did this which I don't think would work(cuase lot's of errors poped up)
Invalid expression term 'select'
and
Expected contextual keyword 'equals'
both at end of here join p in Context.PDFs on c.Ref_PDF
internal List<EF_Model.PDF> Customers_File(int _id)
{
using (var Context = new EF_Model.CoolerEntities())
{
var q = from c in Context.PCs
where c.Ref_Customer == _id
join p in Context.PDFs on c.Ref_PDF
select new { c.PDF.Id, c.PDF.Name, c.PDF.File };
return q;
}
}
How can we make it into a linq statement?
Fix the syntax for the query
List<EF_Model.PDF> Customers_File(int _id) {
using (var Context = new EF_Model.CoolerEntities()) {
var q = from c in Context.PCs
join p in Context.PDFs on c.Ref_PDF equals p.Id
where c.Ref_Customer == _id
select new EF_Model.PDF { Id = c.PDF.Id, Name = c.PDF.Name, File = c.PDF.File };
return q.ToList();
}
}
and the method expects to return a list so use the ToList() on the query when returning from the method.
UPDATE:
If the intention was just to return the PDF model then no need to create the anonymous object just return c.PDF
List<EF_Model.PDF> Customers_File(int _id) {
using (var Context = new EF_Model.CoolerEntities()) {
var q = from c in Context.PCs
join p in Context.PDFs on c.Ref_PDF equals p.Id
where c.Ref_Customer == _id
select c.PDF;
return q.ToList();
}
}
This should do the job for you
from pc in context.PCs where pc.Ref_Customer == _id
join p in context.PDFs on pc.Ref_PDF equals p.Ref_PDF
select new {pc.PDF.Id, pc.PDF.Name, pc.PDF.File }
Probably when you said errors, I assume you saw synactical errors
If you set up a navigation property, the query is:
var q =
from pc in Context.PCs
where pc.Ref_Customer == _id
from pdf in pc.PDFs
select pdf;
If you don't:
var q =
from pc in Context.PCs
where pc.Ref_Customer == _id
join pdf in Context.PDFs on pc.Ref_PDF equals pdf.Id
select pdf;
The main thing to know about the join syntax, it has the form
" join (a) in (b) on (c) equals (d) "
(a): the new range variable for a member of (b)
(b): the source of items you are joining to - the right side of the join.
(c): an expression in which the item from the left side of the join is in scope.
(d): an expression in which the item from the right side of the join is in scope - (a).

Save the result of LINQ query to list

I'm trying to create handler to save the result of LINQ query to list and that what i reached to
public static List<string> Get()
{
LesamisContainer LC = new LesamisContainer();
List<string> list = (from pb in LC.PayBills
join c in LC.Customers on pb.CustomerId equals c.Id
join d in LC.Departments on pb.DepartmentId equals d.Id
select new { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId } into x
select x).Tolist();
return list;
}
but i got this exception
http://i60.tinypic.com/2lxu2o.png
Cannnot convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
You're creating an anonymous type with
select new { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId } into x
The select x just returns this type. To get a List<string> you would need to return on of the properties from this instead, eg: select x.FullName
That would be a pretty odd way of doing things though, and probably not what you really intend. I assume you don't actually want a List<string>.
In which case, since you're returning the result from the method it should be declared and not anonymous:
public class PayBillModel
{
public int Id {get;set;}
...
}
then
select new PayBillModel() { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId }
This way, you end up with a List<PayBillModel>.
You're getting multiple types. Try changing the List type to object instead of string
List<object> list = (from pb in LC.PayBills
join c in LC.Customers on pb.CustomerId equals c.Id
join d in LC.Departments on pb.DepartmentId equals d.Id
select new { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId } into x
select x).Tolist();
You can then browse through the list by:
foreach (object item in list)
{
if (item is pb.Id)
{
//do something
}
//or
//if (item.GetType() == typeof(PayBills)) { }
}

Entity Framework query error?

I'm getting this error:
The entity or complex type 'Model.Members' cannot be constructed in a LINQ to Entities query.
with my code:
public List<Members> getTeamMembers(String tem_reference)
{
var query = from c in cecbContext.Projects
join b in cecbContext.TeamMembers on c.proj_team equals b.team_reference
join d in cecbContext.Members on b.mem_reference equals d.mem_reference
where c.proj_reference == tem_reference
select new Members
{
mem_reference = d.mem_reference
};
return query.ToList<Members>();
}
I believe you're running into problems because you're trying to project a mapped entity, and this answer would tell you more: https://stackoverflow.com/a/5325861/2208058
This is what I think might work for you:
var query = from c in cecbContext.Projects
join b in cecbContext.TeamMembers on c.proj_team equals b.team_reference
join d in cecbContext.Members on b.mem_reference equals d.mem_reference
where c.proj_reference == tem_reference
select d.mem_reference;
return query.Select(ref => new Members { mem_reference = d.mem_reference }).ToList();

How to get back result from a session

Work on entity frame work vs2010
After execute my linq query get a list of records ,want to put this record in session .Now from session Want to get back my record list ,what to do how to get back record from a session
Linq query
public IEnumerable GetSearchUserGroupPermissionData(int userID = 0)
{
var query = from p in this.Context.CmnPermissionGroupUsers
join q in this.Context.CmnPermissionGroups on p.PermissionGroupID equals q.PermissionGroupID
join r in this.Context.CmnPermissionGroupDocs on p.PermissionGroupID equals r.PermissionGroupID
join s in this.Context.CmnUserInfoes on p.UserID equals s.UserID
join t in this.Context.CmnDocLists on r.DocListID equals t.DocListID
//join u in this.Context.CmnModuleFormCompanies on t.ModuleID equals u.ModuleID
//join v in this.Context.CmnModuleLists on u.ModuleID equals v.ModuleID
//join w in this.Context.CmnFormLists on u.FormID equals w.FormID
where p.IsDeleted == false
select new
{
RecordID = p.PermissionGroupUserRecordID,
s.UserID,
s.UserFirstName,
q.PermissionGroupName,
p.EffectiveDate,
p.StatusID,
t.DocListID,
t.DocName,
t.ModuleID,
// v.ModuleName,
// u.FormID,
// t.FormName,
// w.FormName,
t.ParentID,
t.Sequence,
t.IsApprovalRequired,
t.CompanyCategoryID,
t.DocTypeID
//p.CreateBy,
//p.CreateOn,
//p.CreatePc,
//p.UpdateBy,
//p.UpdateOn,
//p.UpdatePc,
//p.IsDeleted,
//p.DeleteBy,
//p.DeleteOn,
//p.DeletePc,
//p.Transfer
};
return query.WhereIf(userID != 0, w => w.UserID == userID).ToList();
}
Put result in session
Session["UserPermission"] = new PermissionGroupUserController().GetSearchUserGroupPermissionData(objEntity.UserID);
Now ,want to get back the record set from session.bellow foreach syntax area as a item contain each row all properties and values but can not assign in a variable just like bellow ,why can not assign an AnonymousType variable value to a variable.
var o = Session["UserPermission"] as IEnumerable; //use casting
foreach (var area in o)
{
//int a = area.UserID;
}
Note:sabove syntax how me error
message:foreach statement cannot operate on variables of type 'object'
because 'object' does not contain a public definition for
'GetEnumerator'
If have any query please ask.
Did you try typecasting oto IEnumerable?
Apart from that, in your foreach loop, you have to use dynamic instead of var. This is required because your type is anonymous.
But i would still strongly suggest you to use normal types instead of Anonumous ones atleast for two reasons
Code reusability.
Better code readability.

Error in LINQ statement when building

In the following LINQ statement I get the error :
Cannot implicitly convert type 'System.Linq.IQueryable' to 'bool'
The 3rd last line has a blue line under the entire line. Here is the code, I tried various changes, i must be missing something obvious, thanks in advance...
var allWaste = _securityRepository.FindAllWaste(userId, SystemType.W);
var searchResults = (
from s in allWaste
where
(
from x in _db.WasteIndicatorItems
join y in
_db.WasteIndicators
on x.WasteIndicatorId equals y.WasteIndicatorId
join z in
_db.HazardTypes
on y.HazardTypeId equals z.HazardTypeId
where
s.WasteId == x.WasteId
group new { x, z } by new { x.WasteId, z.Hazardous } into g
select new
{
nbrOf = g.Count(),
g.Key.Hazardous
}
).Where(a => a.nbrOf >= 1 && a.Hazardous == false)
select s
).Distinct();
The problem is you have an IQueryable in your where clause.
Try
...where( (from x in _db.WasteIndicators ... ).Any() )...
Or something that returns a boolean.

Categories