I have build a query to return data from two tables in which they are joined by inner join. Although, as the query seems fine, i am getting error message when i try to access the selected field names from the query. How do i use .SingleOrDefault() function in this query. Can anybody help me how should i proceed.
private void FindByPincode(int iPincode)
{
using (ABCEntities ctx = new ABCEntities())
{
var query = from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area};
// var query = ctx.Cities.AsNoTracking().SingleOrDefault(_city => _city.Pincode == iPincode);
if (query != null)
{
cboState.SelectedItem.Text =query.State; //Getting error "Could not found"
cboCity.SelectedItem.Text = query.CityName; //Getting error "Could not found"
txtArea.Text = query.Area; //Getting error "Could not found"
}
}
}
Thanks in advance.
Try this:
using (ABCEntities ctx = new ABCEntities())
{
var query = (from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area}).FirstOrDefault();
if (query != null)
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
can it be that you are selecting a field named StateName, and then acessing State.
cboState.SelectedItem.Text =query.State;
cboState.SelectedItem.Text =query.StateName;
Please provide more details on the error and the class structure of your code
Here's how a similar situation worked for me:
using (ABCEntities ctx = new ABCEntities())
{
var query = (from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area}).Single();
if (query.Any())
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
Notice that i used query.Any() up there, that is because query != null will always return true. However any() checks if a query has returned 1 or more records, if yes Any() returns true and if a query returns no records then Any() returns false.
Related
I have a file that where I have rows that need to be inserted into a destination_table. The destination_table is related in the database with another table, we will call it head_table.
I am using a DataTable class to get the data.
I have the following code but I don't get the expected result.
The query returns zero and this must not be so, it must be greater than zero
If someone could guide me a little, thank you very much.
var query =
from file in ta.AsEnumerable()
join head_table in tc.AsEnumerable()
on file["ID"] equals head_table["ID"]
join destination_table in td.AsEnumerable()
on new { ID = file["ID"].ToString().Trim() } equals new { ID = destination_table["ID"].ToString().Trim() }
into gj
from result in gj.DefaultIfEmpty()
select new { line = file, destination_table_key = (result == null ? null : result["ID"]) };
var insertValues = query.Where(a => a.destination_table_key == null);
//It has to return greater than zero and currently I can't get it
if (insertValues.Count() > 0)
{
foreach (var re in insertValues)
{
InsertRow... //Here is the part of the insert
}
}
I need to use Linq to Entity Framework to query a LOCATION table to get the record of the location code with the MAX effective date, then use that result as a join in the next query.
I BELIEVE I need to do convert before the IQueryable is used, because I have that last clause in the second query where I want to exclude records where the FLOOR code is in the excludedSchools list. That excludedSchools list will have the newLocationCode in it.
So, I need to update the values in the IQueryable result before I use it. Can I do this? Here is my code:
using (var db = new TheContext())
{
IQueryable<LocationTable> locatinWithMaxEffDate =
(from lc in db.LocationTable
where lc.EFF_STATUS == "A" && lc.EFFDT <= DateTime.Now
group lc by lc.LOCATION into g
select g.OrderByDescending(x => x.EFFDT).FirstOrDefault()
);
foreach (var location in locatinWithMaxEffDate.ToList())
{
string newLocationCode;
if(codeMappingDictionary.TryGetValue(location.FLOOR, out newLocationCode))
{
// how do I update locatinWithMaxEffDate FLOOR value
// with newLocationCode so it works in the query below?
location.FLOOR = newLocationCode;
}
}
var query =
(from fim in db.PS_PPS_FIM_EE_DATA
join mloc in locatinWithMaxEffDate on fim.LOCATION equals mloc.LOCATION
where
fim.EMPL_STATUS == PsPpsFimEeData.EmployeeStatusValues.Active
&& fim.AUTO_UPDATE == PsPpsFimEeData.AutoUpdateValues.Enabled
&& includeJobCodes.Contains(fim.JOBCODE)
&& !excludedSchools.Contains(mloc.FLOOR)
select new PpsAdministratorResult
{
SchoolId = mloc.FLOOR,
Login = fim.OPRID,
EmployeeId = fim.EMPLID,
}
With the code above, the locatinWithMaxEffDate does not have the updated FLOOR values. I can see why this is, but can't seem to fix it.
So far, I have tried introducing another list to ADD() the new location record to, then casting that as an IQueryable, but I get an error about primitive vs concrete types.
I decided to make things easier on myself. Since both sets of data are very small (fewer than 1000 records each) I call take the entire set of data as an annonymous type:
using (var db = new TheContext())
{
IQueryable<LocationTable> locatinWithMaxEffDate =
(from lc in db.LocationTable
where lc.EFF_STATUS == "A" && lc.EFFDT <= DateTime.Now
group lc by lc.LOCATION into g
select g.OrderByDescending(x => x.EFFDT).FirstOrDefault()
);
var query =
(from fim in db.PS_PPS_FIM_EE_DATA
join mloc in locatinWithMaxEffDate on fim.LOCATION equals mloc.LOCATION
where
fim.EMPL_STATUS == PsPpsFimEeData.EmployeeStatusValues.Active
&& fim.AUTO_UPDATE == PsPpsFimEeData.AutoUpdateValues.Enabled
&& includeJobCodes.Contains(fim.JOBCODE)
select new PpsAdministratorResult
{
SchoolId = mloc.FLOOR,
Login = fim.OPRID,
EmployeeId = fim.EMPLID,
}
}
Then, just work with the two objects:
List<PpsAdministratorResult> administratorList = new List<PpsAdministratorResult>();
foreach (var location in query.ToList())
{
string newLocationCode;
if(schoolCodeMappings.TryGetValue(location.SchoolId, out newLocationCode)) // && newLocationCode.Contains(location.LOCATION))
{
location.SchoolId = newLocationCode;
}
if( !excludedSchools.Contains(location.SchoolId) )
{
administratorList.Add(location);
}
}
Now, I have the list I want.
While trying to see if a table contains a certain set of values I am getting this error. Below is where the error is being thrown. Does anyone know how to get around this exception and still check my table so I can avoid inserting duplicate rows? Thank you!
var qryDepts = from p in AuthContext.Dept_User_Bridge
where p.UserID == editedUser.UserID
select p;
foreach (var dept in editedUser.DeptIDs)
{
var deptObj = new Dept_User_Bridge { UserID = editedUser.UserID, DeptID = dept };
//exception thrown here
if (!qryDepts.Contains(deptObj))
{
AuthContext.Dept_User_Bridge.Add(new Dept_User_Bridge
{
DeptID = dept,
UserID = editedUser.UserID
});
}
}
One thing is you want to load data into Memory with ToList().
var qryDepts = (from p in AuthContext.Dept_User_Bridge
where p.UserID == editedUser.UserID
select p).ToList();
Then, you could try with Any().
if(!qryDepts.Any(x => x.UserID == deptObj.UserID))
{
...
}
I am using LINQ to SQL in my C# tutorial project but I have basic knowledge of it.
I made a SQL query like this:
SELECT ID,HeroName,HeroRarity,Initiative,Attack,Attack1
FROM CharactersName
WHERE ID IN(
SELECT HeroID
FROM Hero_Group
WHERE GroupID=1
)
(Hero_Group) is a table to deal with a many-to-many relation between (CharactersName) table and another table named (Groups) where a character can be in more than one group.
I tried to write it in LINQ like this:
void FilterGroup()
{
HDAEntities db = new HDAEntities();
var query = from obj in db.CharactersNames
where obj.ID == from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new
{
obj2.GroupID
}
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
}
But of course this is gibberish.
Can someone help me, please ? (be informed that I have little knowledge of LINQ to SQL)
~TIA~
You can do it like this:
void FilterGroup()
{
HDAEntities db = new HDAEntities();
var subQuery = db.Hero_Group.Where(h => h.GroupID == comboBox1.selectedIndex)
.Select(h => h.GroupID);
var query = from obj in db.CharactersNames
where subQuery.Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
var result = query.ToList(); // this is where your query and subquery are evaluated and sent to the database
db.Dispose();
db = null;
}
Note that the subQuery is not evaluated until you call ToList(). You also need to dispose the object (or try the using statement to create the HDAEntities object). Also, make sure you don't dispose the db before evaluating the query (calling ToList after Dispose will throw an exception).
var query = from obj in db.CharactersNames
where (from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new {obj2.GroupID}).Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
var query = from obj in db.CharactersNames
where (from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new {obj2.GroupID}).Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
I am using this method to get results to fill my grid but this method is also used to fill another grid which requires a where clause with two params and this one
only needs one. Even though i passed in null of the param that isn't used but still it is returning no results because of the where clause. Any advice of how i could
change this maybe use linq to sql where i call the method to specify the where clause instead of in the method getting data?
DocsForReview.DataSource = docLib.GetGrid(Guid.Empty, lib);
using (var dc = new DocMgmtDataContext())
{
var subs = (from doc in dc.Documents
join u in dc.Users on doc.OwnedByUserID equals u.ID
where doc.OwnedByUserID == usr && doc.LibraryID == lib
select new StudentDocuments
{
DocID = doc.ID,
Assignment = doc.Library.Name,
Submitted = doc.UploadDT,
Student = u.FullName
}).OrderByDescending(c => c.Submitted).AsEnumerable().ToList();
return subs;
}
For nullable types try this:
doc.LibraryID == (lib ?? doc.LibraryID)
In your case (a System.Guid) you can try this:
doc.LibraryID == (lib == Guid.Empty ? doc.LibraryID : lib)