Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Why below error is coming in code ? What I do?
public ActionResult Edit(int? id)
{
Emp emp = from c in db.Emps.Where(e => e.EmpId == id).Select(c).SingleOrDefault();
EmpModel model = new EmpModel()
{
EmpId = emp.EmpId,
EmpName=emp.EmpName,
EmpJob=emp.EmpJob,
EmpSalary=emp.EmpSalary,
DeptId=emp.DeptId
};
return View(emp);
}
Errors:
1)The name 'c' does not exist in the current context Error:
2) A query body must end with a select clause or a group clause
Click here to see Image
Because you have used the select extended method which requires you to select needed fields that you want in your Emp object. By the way you Don't really need to use From a in db when you are using LINQ Query Syntax
for example:
Emp EmpObj = Db.Emps.Where(e => e.EmpId == id).Select(x => x.EmpName).SingleOrDefault();
This select query will return only one specific value. But if you need multiple parameters out from it. You can return an object from Select extended Method like this:
.Select(x => new {x.Name, x.Address, x.Gender} ).SingleOrDefault();
Hope that helps and Please, before you question again do read; How should i ask a good question?
You don't need the from c in part for this syntax, and you can simplify the rest quite a bit as well:
Emp emp = db.Emps.SingleOrDefault(e => e.EmpId == id);
Try below code
EmpModel model = db.Emps.Where(e => e.EmpId == id).Select(x => new EmpModel { EmpId=x.EmpId , EmpName =x.EmpName, EmpJob =x.EmpJob, EmpSalary=x.EmpSalary, DeptId=x.DeptId }).SingleOrDefault();
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i have this query in SQL Server
select max(win_votos), win.cdt_id, cdt_nome
from tb_ganhadores_win as win
inner join tb_candidatos_cdt as cdt on cdt.cdt_id = win.cdt_id
group by win.cdt_id,cdt_nome
<--
and i need to create a list 'AspNetMvc' page, like
public ActionResult ListWinners(int? id){
LINQ QUERY HERE
return View('that list');
}
sorry about my english
can anyone help me please?
var res= (from win in dbContext.tb_ganhadores_wins
join cdt in dbContext.tb_candidatos_cdts
on win.cdt_id equals cdt.cdt_id
select new {win,cdt})
.GroupBy(x=>new{Id=x.win.cdt_id,Nome=x.cdt.cdt_nome})
.Select(x=>new
{
Votos=x.Max(z=>z.win.win_votos),
Id=x.Key.Id,
Nome=x.Key.Nome
})
.ToList();
If you use entity framework and your model name is like this you can use some think like this:
var result = from win in tb_ganhadores_win
join cdt in tb_candidatos_cdt on cdt.cdt_id = win.cdt_id
group win by new { win.cdt_id, cdt_nome } into g
select new
{
max = g.Max(win_votos),
win.cdt_id,
cdt_nome
};
and return result.ToList();
note :
"tb_ganhadores_win"
and
"tb_candidatos_cdt"
is your models.Replace it by what you want
I have an MVC 3 project in Visual Studio c#. I have a LINQ to SQL query which works fine and by following an example listed elsewhere on stackoverflow:
Comparing two lists using linq to sql
I have been able to successfully reduce my results where my two nested collections match. This is the bit of code that did the trick (example from the link above):
var anyDesiredSkills = canidateSkills.Any( c => desiredSkills.Select( ds => ds.SkillId ).Contains( c.SkillId ) );
I've adapted this successfully, but now I need to be able to filter records using more than one condition. I was wondering if anyone would be able to adapt the above to show how you could include more than one condition?
To give you some background on what my goal is:
A search page where you can select any number of contacts
Each contact added to the search criteria may/may not have a 'role' assigned. If a role is present this should be factored in to the query.
Results returned based on this dynamic criteria.
Thanks in advance for any and all help :O)
It sounds like you're looking for something like:
var desiredSkillIds = desiredSkills.Select(_=>_.SkillId).ToList();
var matchingContacts =
from contact in Contacts
where contact.Role == null || desiredRoles.Contains(contact.Role)
where contact.Skills.Any(cs=> desiredSkillIds.Contains(cs.SkillId))
select contact;
Or in method-based syntax:
var matchingContacts = Contacts
.Where(contact => contact.Role == null || desiredRoles.Contains(contactRole))
.Where(contact => contact.Skills.Any(cs => desiredSkillIds.Contains(cs.SkillId)));
Here's the final code I used:
servicelist = servicelist.Where(
d => d.ContactSelection.Any(
h => model.ContactFilter.Select(ds => ds.StaffNumber).Contains(h.StaffNumber)
&&
model.ContactFilter.Select(ds => ds.ContactRole).Contains(h.ContactRole) || model.ContactFilter.Select(ds => ds.StaffNumber).Contains(h.StaffNumber) && model.ContactFilter.Select(ds => ds.ContactRole).Contains("0"))
);
Note that the last filter .Contains("0) is the value of '-- select role --' which is an option injected in to the drop down. Hope this helps anyone else!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“NOT IN” clause in LINQ to Entities
I work with the schema below, and I want to know how I can write in the sql query in LINQ to Entities.
SQL Code:
Select *
FROM GROUEPUSERS G
WHERE G.IDGROUPE NOT IN (SELECT IDGROUPE
FROM APPARTENIR
WHERE IDCLIENT = id)
The ID is a variable that I will recover. The problem is that the table APPARTENIR becomes a navigation table.
I found the solution just in case :
var groups = from g in context.GROUPEUSER
where !g.UTILISATEUR.Select(d => d.ID).Contains(id)
select g;
You can write something like that:
var query = myEntities.Groupeusers
.Where(gu => !myEntities.Utilisateur.Any(ut => ut.idgroupe == gu.idgroupe)).ToList();
That should work.
EDIT:
Try that query instead:
var query = myEntities.Groupeusers
.Where(gu => !myEntities.Utilisateur
.SelectMany(ut=>ut.Groupeuser)
.Any(gu => gu.Idgroupe == gu.Idgroupe)).ToList();
OR maybe even better:
var query = myEntities.GroupeUsers
.Except(myEntities.Utilisateur.SelectMany(ut => ut.Groupeuser))
.ToList();
EDIT2:
If I understand your query correct, you would like to identify a special user entity.
var query = myEntities.GroupeUsers
.Except(myEntities.Utilisateur.Where(u => u.IdUser == id).SelectMany(ut => ut.Groupeuser))
.ToList();
I'm attempting to write a search function for a database table that needs to access information from related tables using Entity Framework. However, I'm running into problems getting the data back out of my initial query after doing a join on the parent table and the related tables. My code currently looks like this. I initialize my queryable object
IQueryable<PurchaseOrder> po = _context.PurchaseOrders;
Where PurchaseOrder is an Entity type. Then there is a series of blocks like this.
if (!String.IsNullOrEmpty(searchViewModel.Comment)){
var helper = _context.PurchaseOrderComments.Where(x => x.CommentText.Contains(searchViewModel.Comment));
var mid = po.Join(helper, r => r.PurchaseOrderID, u => u.PurchaseOrderID, (r, u) =>
new
{
PurchaseOrderID = r.PurchaseOrderID,
PurchaseOrderNumber = r.PurchaseOrderNumber,
VendorID = r.VendorID,
ContractNumber = r.ContractNumber,
BuyerUserID = r.BuyerUserID
});
po = mid.Select(x => new PurchaseOrder
{
PurchaseOrderID = x.PurchaseOrderID,
PurchaseOrderNumber = x.PurchaseOrderNumber,
VendorID = x.VendorID,
ContractNumber = x.ContractNumber,
BuyerUserID = x.BuyerUserID
});
}
After each block, po is passed to the next search parameter. However, as you might guess, my program complains that I can't build a complex type in mid's Select statement. I've also tried building PurchaseOrder objects from the contents of mid, inserting them into a new List of PurchaseOrders, and converting that list into a queryable to assign to po to pass on to the next block. However, that changes po's data type from System.Data.Object.ObjectSet to System.Collections.Generic.List, which then throws an InvalidOperationException the next time I try and iterate through it using a foreach.
So my question is, are there any obvious mistakes in my approach or any suggestions for other ways to approach the problem? Thanks very much for any help.
I think you're making this more complicated than it needs to be. If I understand what you're trying to do, you should be able to do something like this:
if (!String.IsNullOrEmpty(searchViewModel.Comment)){
po = po.Where(
o => o.PurchaseOrderComments.Any(
c => c.CommentText.Contains(searchViewModel.Comment)));
}
StriplingWarrior's solution is the best way. In case that your PurchaseOrder class really doesn't have a navigation collection of PurchaseOrderComments (which would force you to use a join) the following should work and is simpler as your double projection:
po=po.Join(helper, r => r.PurchaseOrderID, u => u.PurchaseOrderID, (r, u) => r);
Not sure how this is done, I have my .edmx set up so that the navigation properties match the foreign key relationships on the tables. Not sure if I still need to perform joins or if EF will give me access to the related table data through the navigational properties automatically.
What I need to do it get all the ContentSections and their associated ContentItems based on the ContentView and filtered by the DiversionProgram.CrimeNumber.
I would like to get back IEnumerable, for each ContentSection it should have access to it's ContentItems via the navigation property ContentItems
Thanks
Something like:
using(Entities context = new Entities())
{
IEnumerable<ContentSection> enumerator = context.ContentSections
.Include("ContentItems")
.Where<ContentSection>(cs => cs.ContentView.ContentViewID == someID && cs.ContentItems.Where<ContentItem>(ci => ci.DiversionProgram.CrimeNumber == someCrimeNumber))
.AsEnumerable<ContentSection>
}
I've interpreted
based on the ContentView
as cs.ContentView.ContentViewID == someID
This will give you all the ContentSections for a given ContentView. And interpreted
filtered by the DiversionProgram.CrimeNumber
as cs.ContentItems.Where<ContentItem>(ci => ci.DiversionProgram.CrimeNumber == someCrimeNumber)
which will give you all those ContentItems that have a specific CrimeNumber.
Or did you mean something else with based on / filtered by. Maybe OrderBy, or all those ContentSections where Any of it's ContentItems would have a certain CrimeNumber?
You can eager load to get all associated records, but when you want to start filtering/ordering, don't bother with Include.
Just do a projection with anonymous types and EF will work out what it needs to do. It's a bit hairy, but it'll work. If it get's too complicated, bite the bullet and use a SPROC.
Now, with that caveat, something like this (off the top of my head):
var query = ctx.ContentView
.Select(x => new
{
ContentSections = x.ContentSections
.Where(y => y.ContentItems
.Any(z => z.DivisionProgram.CrimeNumber = 87))
}).ToList().Select(x => x.ContentSections);
If you use the CTP5 you can do something very unique it looks like this:
var context = new YourEntitiesContext();
var query = context.ContentView.Include(cs => cs.ContentSections
.Select(ci => ci.ContentItems
.Select(dp => dp.DiversionProgram)
.Where(dp.CrimeNumber == crimeNumber)))
.Where(cv => cv.ContentViewID == contentViewID).FirtsOrDefault();
You can learn more about the CTP5 and how it can be used in Database first scenario here
var query = from t1 in studentManagementEntities.StudentRegistrations
join t2 in studentManagementEntities.StudentMarks
on t1.StudentID equals t2.StudentID
select new
{
t1.selected column name,
t2.selected column name
};