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.
Related
I have two tables (tbPerson and tbDataLog) where I need to return Id from one table (tbPerson) after checking certain conditions on both. After this, this result should be passed to another query. My first query returns the Id (primary key of a table) successfully and I need to pass these ids to another query so that it return me data based upon these Id. I also has an IQueryable type base object to check certain conditions to fetch data.
IQueryable<tbPerson> dataset
and I cannot changes this from Iqueryable to other as it will break other part of the code)
My first linq statement:
public static IQueryable<LogResults> GetResultsForYes()
{
Databasename ents = new Databasename();
var ids = (from f in ents.tbPerson
join g in ents.tbDataLog
on f.InfoID equals g.RefId
where g.Tag == "subscribed" && g.OldValue == "No" && g.Action == "Modified"
select new LogResults { _LogID = f.Id }).OrderBy(x => x._LogID);
return ids;
}
public class LogResults
{
public int _LogID { get; set; }
}
I access my result something like this where I can see in debugger all the Ids.
IQueryable<LogResults> log = GetResultsForYes();
Problem comes, when I tried to get records from tbPerson based upon these returned Id.
dataset=log.where(x=>x._LogID != 0);
I get this error:
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists(are you missing a cast)?
Any suggestions or some other good approach is welcome.
I love this thing about stackoverflow. when we write questions we force our brain to think more deeply and after 30 mins of posting this question, I solved it in a simple way. Sometimes we overcomplicated things!
var ids = (from f in ents.tbPerson
join g in ents.tbDataLog
on f.InfoID equals g.RefId
where g.Tag == "subscribed" && g.OldValue == "No" && g.Action == "Modified"
select new { f.Id }).ToArray();
var allId = ids.Select(x => x.Id).ToArray();
dataset = dataset.Where(x => allId.Contains(x.Id));
#ankit_sharma : I have not tested yours but will give a try and come back to you. Thanks for giving time and effort.
IQueryable<tbPerson> dataset=log.where(x=>x._LogID != 0);
The result of log.where(x=>x._LogID != 0) is an IQueryable<LogResults>, and you are trying to assign this result to dataset of type IQueryable<tbPerson>, two diferent types.
EDIT:
I see you make a join to get the tbPerson ids, and then you do a second query to get the persons. You could get the persons in the first join.
I just modify your code:
IQueryable<tbPerson> persons = from person in ents.tbPerson
join g in ents.tbDataLog
on person.InfoID equals g.RefId
where g.Tag == "subscribed" && g.OldValue == "No" && g.Action == "Modified"
select person;
I am implementing a controller and I need to get all staff members which have a certain RiskTypeID, which will be selected by the user when they click on Navigation Item.
Here is how I would create the joins in SQL
SQL
Select
RTHG.RiskTypeID,
SM.FullName
From RiskTypeHasGroup RTHG
Inner join RiskGroup RG On RTHG.RiskGroupID = RG.ID
Inner join RiskGroupHasGroupMembers RGHGM ON RG.ID = RGHGM.RiskGroupID
Inner Join GroupMember GM ON RGHGM.GroupMemberID = GM.ID
Inner Join GroupMemberHasStaffMember GMHSM ON GM.ID = GMHSM.GroupMemberID
Inner Join StaffMember SM ON GMHSM.StaffMemberID = SM.ID
Where RTHG.RiskTypeID = 1
I’ve pulled back data before using Linq and lambda but only using simple expressions, I now need to be able to make a call which will bring back the same data as the sql outlined above, I’ve searched online but can’t find anything similar to my requirement.
Here is my Controller, I placed comments inside as guidance
Controller
public ActionResult ViewRiskTypes(int SelectedRiskTypeID)
{
var RiskTypes = _DBContext.RiskTypes.ToList(); // Get all of the current items held in RiskTypes tables, store them as a List in Var RiskTypes
var ViewModel = new List<RiskTypeWithDetails>(); // Create colletion which holds instances of RiskTypeWithDetails and pass them to the ViewModel
var Details = new RiskTypeWithDetails(); // Create a new instance of RiskType with details and store the instance in var Details
foreach (var RiskType in RiskTypes) // Loop through each Item held in var RiskTypes
{
Details.RiskTypes.Add(new RiskTypesItem { ID = RiskType.ID, Description = RiskType.Description }); // assign each items ID & Description to the same feilds in a new
// instance of RiskTypeItems (which is a property of RiskTypeWithDetails)
}
foreach (var RiskType in RiskTypes) // Loop through each item in RiskTypes
{
if (RiskType.ID == SelectedRiskTypeID) // Check Item ID matches SelectedRiskTypeID value
{
//var Details = new RiskTypeWithDetails();
Details.RiskTypeDescription = RiskType.Description; //assign the Risk type Descripton to RiskTypeWithDetails RiskTypeDescription Property
Details.RiskDetails = _DBContext
.RiskTypeHasGroups
//.GroupMemberTypeHasGroupMembers
.Where(r => r.RiskTypeID == SelectedRiskTypeID) // Where RiskTypeId matches Selected ID bring back following data from Db
.Select(r => new RiskDetails
{
RiskGroupDescription = r.RiskGroup.Description,
GroupMembers = r.RiskGroup.RiskGroupHasGroupMembers
.Select(v => v.GroupMember).ToList(),
//StaffMembers = r.RiskGroup.RiskTypeHasGroups
// .Join(r.RiskGroup.RiskTypeHasGroups,
// a => a.RiskGroupID , b => b.RiskGroup.ID,
// (a, b) => new {a, b})
// .Join(r.RiskGroup.RiskGroupHasGroupMembers,
// c => c.) // Dosent join as I would expect... no idea what to do here
}).ToList();
ViewModel.Add(Details); //Add all data retrieved to the ViewModel (This creates one item in the collection)
}
}
return View(ViewModel);
}
As you will see I want to get all Staff Members with a match for the selected RiskTypeID. I need some assistance in converting the above SQL to work within my controller as a lambda expression
Thanks in advance
You were on the right track with your commented out code! For starters, LINQ has two different sytaxes: query and method chain. You were using the method chain syntax and it can get really unmaintainable really quickly.
For an instance like this, query syntax is where it's at.
Here's the result:
from rhtg in _dbContext.RiskTypeHasGroup
where rhtg.RiskTypeID == 1
join rg in _dbContext.RiskGroup
on rhtg.RiskGroupID equals rg.ID
join rghgm in _dbContext.RiskGroupHasGroupMembers
on rg.ID equals rhtg.ID
join gm in _dbContext.GroupMember
on rg.ID equals gm.ID
join gmhsm in _dbContext.GroupMemberHasStaffMember
on gm.ID equals gmhsm.GroupMemberID
join sm in _dbContext.StaffMember
on gmhsm.StaffMemberID equals sm.ID
select new
{
rhtg.RiskTypeId,
sm.FullName
};
Do note, that I used .Net conventions for the different variables.
Here's some documentation on the query syntax:
https://msdn.microsoft.com/en-us/library/gg509017.aspx
You can write the exact same query in linq as follows:
var query = (from RTHG in _DBContext.RiskTypeHasGroup RTHG
join RG in _DBContext.RiskGroup on RTHG.RiskGroupID equals RG.ID
join RGHGM in _DBContext.RiskGroupHasGroupMembers on RG.ID equals RGHGM.RiskGroupID
join GM in _DBContext.GroupMember on RGHGM.GroupMemberID = GM.ID
join GMHSM in _DBContext.GroupMemberHasStaffMember on GM.ID equals GMHSM.GroupMemberID
join SM in _DBContext.StaffMember on GMHSM.StaffMemberID equals SM.ID
where RTHG.RiskTypeID == 1
select new {RTHG.RiskTypeID,SM.FullName});
I'm trying to store the foreach loop collection of data outside the loop for later use.
Consider the following foreach loop.
IList<DetailViewModel> storeAllLoopItems = new List<DetailViewModel>();
foreach (var item in _listOfItems)
{
var items =
(from a in context.Employee
join b in context.Orders on a.Id equals b.Id
join d in context.Notes on a.Id equals d.Id
where a.Id == item.id
select new DetailViewModel
{
Name = b.LegalName,
Abbrev = c.Abbrev,
TaxAmount = a.Amount,
}).ToList();
storeAllLoopItems.Add(items); //<<<ERROR
}
Error:
The best overloaded method match for
'System.Collections.Generic.List.Add(DetailViewModel)'
has some invalid arguments
cannot convert from 'System.Collections.Generic.List'
to 'DetailViewModel'
Add method is for adding a single value. You will need to add the items into the list by hand, because the IList interface has no AddRange method. Or change the definition to be List<DetailValueModel> which has an AddRange method.
Aslo, the .ToList() is not required and wastes memory.
I have this query that I am performing using entity framework 5 with MySql.
var employeeDetails = (from em in entities.employeemasters.AsEnumerable()
join sf in entities.salaryfitments.AsEnumerable()
on em.empID equals sf.empID into emsf
from x in emsf
where (x.edCode.ToString().Trim().Equals(txtEDCode.Text)
&& x.edCode != "SYS001")
select new { em, x });
The where (x.edCode.ToString().Trim().Equals(txtEDCode.Text) checks to see if there are any earnings/deductions stored for that employee and if so I can be able to get the amount figure.
I would like the query to return all employees and if they do not have a particular earnings/deductions matching txtEDCode.Text, then return a default value.
I cannot place .DefaultIfEmpty() after where (x.edCode.ToString().Trim().Equals(txtEDCode.Text)
What should I do to get the appropriate results?
Instead of returning the whole entities I'd create a new object with only the fields I was interested in and use a ternary if to provide the default value in the select statement, for example.
select new {
name = x.Name,
salary = x.Salary,
code = string.IsNullOrEmpty(x) ? "Blah" : x
}
I have a database that looks like this:
tbl_Seminar
ID
isActive
tbl_SeminarFees
ID
seminar_id -- foreign key
fee_text
I want to get all seminars that are active (isActive ==1) and a list of the fees associated with that seminar. Each Seminar may have n records in tbl_SeminarFees that are its fees. I am able to return a linq structure that returns me a list of objects that look like this {seminar, SeminarFee} but I wanted to create a nested structure that looks like this:
{seminar, List<SeminarFee>}
What should my linq query look like?
here is my linq currently:
var results = from s in context.Seminar
join p in context.SeminarFees on
s.ID equals p.SeminarID
where s.IsActive == 1
select new
{
Seminar = s,
Fees = p
};
How do I change this to get a list of these: {seminar, List<SeminarFee>}
Thanks
UPDATE
#lazyberezovsky gave me a good idea to use a group join and into another variable. But then how do I loop through the result set. Here is what I have now:
foreach (var seminarAndItsFeesObject in results)
{
//do something with the seminar object
//do something with the list of fees
}
This however gives me the following error:
Argument type 'SeminarFees' does not match the
corresponding member type
'System.Collections.Generic.IEnumerable`1[SeminarFees]'
What am I doing wrong?
Thanks
You can use group join which groups inner sequence items based on keys equality (a.k.a. join..into) to get all fees related to seminar:
var results = from s in context.Seminar
join f in context.SeminarFees on
s.ID equals f.SeminarID into fees // here
where s.IsActive == 1
select new
{
Seminar = s,
Fees = fees
};
You can't call ToList() on server side. But you can map results on client later.
BTW You can define navigation property Fees on Seminar object:
public virtual ICollection<SeminarFee> Fees { get; set; }
In this case you will be able load seminars with fees:
var results = context.Seminar.Include(s => s.Fees) // eager loading
.Where(s => s.IsActive == 1);
var results = from s in context.Seminar
join p in context.SeminarFees on s.ID equals p.SeminarID
where s.IsActive == 1
group p by s into grouped
select new {
Seminar = grouped.Key,
Fees = grouped.ToList()
};