I have a schedule object that is returned from the database. It contains information from a few tables. One of the tables is called ScheduleData and has four columns. It has this format:
Id | ScheduleId | Name | Value
I need the value of the fourth column where the Name is Mine and the ScheduleId is 5
I have tried this, but it doesn't work:
string val = from s in schedule.ScheduleData where s.Name.Equals("Mine") && s.ScheduleId == 5 select s.Value;
Use First method or FirstOrDefault method.The query returns an IEnumerable<T>, you can't assign it to string.
string val = (from s in schedule.ScheduleData
where s.Name == "Mine" && s.ScheduleId == 5
select s.Value).First();
Related
Here is the table setup I have:
int | Design_1
0 | Design_A
1 | Design_B
2 | Design_C
Here is my code for the form:
var design = (from d in BikePartsDataContext1.handlebars
where d.#int == "0"
select d.Design_1);
this.textBox1.Text = design.ToString();
What I am trying to do is make the textBox1 text have the value of the Design_1 value from the row where #int is 0.
All works fine until I get this as the text value for textBox1:
SELECT [t0].[Design 1] FROM [dbo].[handlebars] AS [t0] WHERE [t0].[int] = #p0
I think you want the first record then based on Id?
// at top of file so you can use the extension methods
using System.Linq;
// code
var design = (from d in BikePartsDataContext1.handlebars
where d.#int == 0 // i removed the quotes add them back if this is truely a string/sql varchar
select d.Design_1).Single(); // use single to ensure only 1 record will get selected
this.textBox1.Text = design; // design will now be the value of Design_1
Some notes:
Single will throw an exception if no records are found OR if more than one record is found.
If there can be 0 records use SingleOrDefault
If there can be more than 1 record and you do not care which one is used then use First or FirstOrDefault
I assumed your id was an int and not a string so I removed the quotes around 0, add them back if this is not the case
You can also rewrite it using only lambda expressions:
this.textBox1.Text = BikePartsDataContext1.handlebars
.Where(x => x.#int == 0)
.Select(x => x.Design_1)
.Single();
This takes a little bit of setup to explain. I know "nulls are bad" in a database and I am experiencing why that can be so, but I have no choice about the way the business uses the data source. The data source has nulls in the dataset and I have to work with it as-is. (Hopefully this addresses the anticipated "Well, your dataset shouldn't have nulls..." or "Why don't you just remove the nulls...?")
Suppose I have sample set like this, where "NULL" is an actual null:
Campus | Name | Relationship
---------------------------------
A | Bob | Relationship 1
B | Bill | NULL
B | Carol | Relationship 2
C | Sally | Relationship 1
Now suppose I am using an option list to filter the results by a distinct list of the values in the Relationship column:
All (meaning show all records)
NULL
Relationship 1
Relationship 2
If I didn't have the "All" option, it would be simple enough:
private IEnumerable<RwsBasePhonesAndAddress> PopulateQuery(string SelectedCampus,
string SelectedRelationship)
{
IEnumerable<RwsBasePhonesAndAddress> query =
db.RwsBasePhonesAndAddresses.Where(m => m.Campus == SelectedCampus);
if (!string.IsNullOrEmpty(SelectedRelationship))
query = query.Where(m => m.Relationship == SelectedRelationship);
else
query = query.Where(m => m.Relationship == null);
query = query.OrderBy(m => m.StudentName).AsEnumerable();
return query;
}
I have verified that the code as written returns results matching the "SelectedRelationship" parameter, including "NULL" records when "NULL" is chosen as a filter.
It's the inclusion of the "All" in the option list that makes this difficult. If the "Relationship" column had no nulls, I could use a null SelectedRelationship parameter as the "do not filter by 'SelectedRelationship'" option.
Is there some way that I can use a "do not filter" option into the code?
Not completely sure that I understood the question. From what I understood to the code above you are missing the part that if you get an "All" value then not to filter out anything. Right? If so:
private IEnumerable<RwsBasePhonesAndAddress> PopulateQuery(string SelectedCampus,
string SelectedRelationship)
{
IEnumerable<RwsBasePhonesAndAddress> query =
db.RwsBasePhonesAndAddresses.Where(m => m.Campus == SelectedCampus);
if(string.IsNullOrEmpty(SelectedRelationship))
query = query.Where(m => m.Relationship == null);
else if (SelectedRelationship != "All")
query = query.Where(m => m.Relationship == SelectedRelationship);
query = query.OrderBy(m => m.StudentName).AsEnumerable();
return query;
}
Good Morning,
I wonder if there's any method within the NHIBERNATE to which I can retrieve the first row of the table?
For example:
Line | ID | Name |Last Name |
1 | 0 | Test | of Information |
2 | 1 | Mauricio | Silva |
If I want the first line or the line 1 of the table
You can use Linq to create queries with nHibernate. There is a method called FirstOrDefault() which takes only the first record. If the query return empty, the FirstOrDefault method will return null, so, remember to check the result before using, for sample:
var firstItem = session.Query<Entity>().FirstOrDefault();
if (firstItem != null)
{
string name = firstItem.Name;
// use object
}
NHibernate does support paging, so we can select "any" record using the .Take() and .Skip(). In our case we can do it like this:
var list = session
.QueryOver<Person>()
.Take(1) // this will take just a first record
//.Skip(0) // we can even skip some, to get next page
;
Then the resulting list will contain 1 or none row...
var person = list.FirstOrDefault();
Also, we can never be sure, what order will be used by DB engine, so we should use explicit ORDER BY:
var list = session
.QueryOver<Contact>()
.OrderBy(p => p.ID)
.Asc
.Take(1)
;
Now we can be sure, that the first result will be with ID == 0
I am using ADO.NET query to select the employee id's of all the employees whose have a location x, y or z and are working under a supervisor.
This is the query that I am working with:
SELECT e.Employee_OID
FROM Employee e
WHERE EXISTS (SELECT 1
FROM Employee e1
WHERE e.Employee_OID = e1.Supervisor_OID
AND e1.Active_f = 'A')
AND e.Location_OID IN (123, 22)
AND e.Active_f = 'A'
I want to convert this is into a LINQ expression, I am a beginner to LINQ and EF, can someone guide me into writing this into LINQ?
This is what I have so far:
var supervisors = (from employee in Employee
where employee.location_OID == "???" //I have ID's in a list here
select employee.Employee_OID).Any();
If you're using EF 4.0 or higher, you can use Contains() to check if an item is in a list:
where yourList.Contains(employee.location_OID)
The exists subquery could be done with Any():
where employee.Any(e1 => e.Employee_OID == e1.Supervisor_OID &&
e1.Active_f == "A")
I have a self referencing table "Product" with the following structure (where D = Draft and A = Approved)
ID ParentID Status Name
---------------------------
1 NULL A Foo
2 1 A Foo2
3 NULL D Bar
4 1 D Foo3
A row can either be "new" (where ParentID == null) or can be a version of an existing row. So we can see from the table that there are 3 versions for the item "Foo" and only 1 for "Bar".
I need a way of returning the latest versions of each item based on whether the user is able to see only "Approved" items or is able to see "Draft" as well. So for example
Users who can see "D" would have:
3 NULL D
4 1 D
The "latest" row for "Foo" and "Bar".
Users who can see "A" would have:
2 1 A
ie. only the "Approved" versions.
Thanks in advance,
Jose
Here is the Linq query that should work for you:
bool hasDraftAccess = false;
var query = DataContext.Records.AsQueryable();
if (!hasDraftAccess) {
query = query.Where(r => r.Status == 'A');
}
var seriesQuery = query.Select(r => new { Record = r, SeriesID = r.ParentID ?? r.ID });
var latestQuery = seriesQuery.GroupBy(s => s.SeriesID).Select(g => g.OrderByDescending(s => s.Record.ID).First());
var resultsQuery = latestQuery.Select(s => s.Record);
var results = resultsQuery.ToArray();
Here's what's happening:
First, add a WHERE clause to filter out draft records if the user doesn't have access to them
Then add a pseudo column called 'SeriesID' that groups all the related versions into that one column. That is, make it easy to group parent and related children.
Group the related records and then pick whichever record is most recent
Select the Linq Entity from the anonymous type so that it is updatable
I should note that if you have the ability to change your data schema you should consider adding a column called InsertDate or something to that effect. Right now I am assuming that whatever record has the highest ID is the latest. It is often better to add a DateTime field and sort on that instead.
I apologize that this isn't actually using Linq syntax--I prefer fluent coding styles--but it could be easily translated to Linq syntax if you preferred it.
Totally untested - but something like this might work, if I've understood the question correctly.
Can see approved
context.Table.Where(p => p.Status == "A")
Can see approved and draft
context.Table.Where(p => p.Status == "D" || (p.Status == "A" && !context.Table.Any(q => q.Status == "D" && q.Parent == p.Parent)))