I have an sql statement like this:
select distinct(agent_name)
from properties
where agent_name not in ('null','')
I want the linq query in C# page
Assuming you're comparing to the string value 'null' like your original query:
List<string> agentNames = db.Properties.Where(p=>p.AgentName != "null" &&
p.AgentName != "")
.Select(p => p.AgentName)
.Distinct()
.ToList();
If you're actually comparing to a null value just change it to:
List<string> agentNames = db.Properties.Where(p=>p.AgentName != null &&
p.AgentName != "")
.Select(p => p.AgentName)
.Distinct()
.ToList();
var result = context.Properties.Where(p => p.AgentName != null
&& p.AgentName != "")
.GroupBy(p => p.AgentName)
.Select(g => g.Key);
Try something like this
var result = (from dbo in database.Table
where dbo.agent_name!=null and dbo.agent_name !=''
select dbo.agent_name).Distinct();
or if you have a list already
var result = (list.Where(a => a.agent_name!=null && a.agent_name!='').Select(
a.agent_name)).Distinct();
You can use it like this
var forms = db.properties.
Where(a => a.agent_name == 'null' || a.agent_name == null).
Select(x => x.agent_name).
Distinct().
ToList();
Its equivalent SQL statement, which is designed by LINQ to SQL is
SELECT
[Distinct1].[agent_name] AS [agent_name]
FROM ( SELECT DISTINCT
[Extent1].[agent_name] AS [agent_name]
FROM [dbo].[properties] AS [Extent1]
WHERE [Extent1].[agent_name] = N'null' OR [Extent1].[agent_name] = N''
) AS [Distinct1]
Related
This question already has answers here:
Linq to SQL multiple conditional where clauses
(3 answers)
Closed 7 years ago.
I want to have multiple where clauses in linq but out of them only one should execute, i was trying something like this:
public JsonResult GetPost(int? id, int? tagid, DateTime? date)
{
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where((x => x.NeighbourhoodId == id) || (y => y.PostedDate == date) || third condition).ToList()
but i was unable to put second and third condition there becoz after putting dot after y, i cant see any options.
Now, out of these three, only one parameter would have value and other two would have null so, it should checks for parameter only with value.
should i write query like this, is it correct way:
if (id != null)
{
//whole query here
}
else if (tagid != null)
{
//whole query here
}
else (date != null)
{
//whole query here
}
Is it the best way to do this or something else is possible. many many thnks in advance for any suggestion.
Something like this?
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId) &&
x.<condition> == (tagid ?? x.<condition>) &&
x.PostedDate == (date ?? x.PostedDate).ToList();
Or like this:
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where(x => id.HasValue ? x.NeighbourhoodId == id :
tagid.HasValue ? x.<condition> == tagid :
x.PostedDate == date).ToList();
Another option is to build your query more dynamically. I think this also makes your code more human readable, and your conditions can be more complex if needed (for example, build your query inside a loop or something). And you can use this with any other operator, like Include etc. Once your query is built, you can call ToList().
var ret = db.Posts.Include(x => x.Tags).Include(x => x.Neighbourhood);
if (id != null)
{
ret = ret.Where((x => x.NeighbourhoodId == id);
}
else
{
...
}
var result = ret.ToList();
You could use the following:
var ret = from data in db.Posts.Include(x => x.Tags)
.Include(x => x.Neighbourhood)
.Where(x => id == null || x.NeighbourhoodId == id)
.Where(x => date == null || y.PostedDate == date)
.ToList();
If the paramter is null, the where-clauses returns every element of the sequence. If its not null it only returns the elements which matches.
I have the following query:
orderMessageEmail.MessageChain = DbContext.Current
.Messages
.Where(c =>
c.OrderId == orderMessageEmail.OrderId &&
c.IsPublic &&
c.MessageId != orderMessageEmail.MessageId &&
c.MessageId < orderMessageEmail.MessageId
)
.Select(c => new OrderMessageChain()
{
CreateDateTime = c.CreateDateTime,
MessageId = c.MessageId,
Message = c.MessageData,
UserFirstName = c.User.FirstName,
UserLastName = c.User.LastName,
CustomerFirstName = c.CustomerAccountPerson.FirstName,
CustomerLastName = c.CustomerAccountPerson.LastName,
SentFrom = c.SentFrom
})
.OrderByDescending(c => c.MessageId)
.Take(10)
.ToList();
The problem I'm running into is that whenever c.User is null it doesn't return ANY record for the OrderMessageChain
I'd like to just have it return UserFirstName and UserLastName as empty strings instead of completely eliminating that OrderMessageChain from the list.
Does this make sense?
One more thing..
Simply testing this query:
var t = DbContext.Current
.Messages
.Include("User")
.Where(c =>
c.MessageId < 138120 &&
c.OrderId == 170496 &&
c.IsPublic)
.ToList();
When I manually execute the same query in the DB i'm shown 3 records, however t is showing zero.
I always thought Include worked as a Left Join - is that not the case?
One more thing...
OK so i think i'm starting to realize what is going on here..
I didn't realize this, but it appears that the DBA setup the DB field UserId on the Message Table to NOT be nullable, however, in the case when there isn't a user record the UserId field contains a 0 (zero) value, instead of null... argh...
I think this is leading to code first to believe it should perform an inner join instead of a left join per here
So i'm not quite sure how to fix this.. is there anyway I can force code first to somehow perform a left join on that navigation property instead of an inner?
You should be able to select the data you need, convert it to an IEnumerable and do the mapping in-memory, something like (the untested);
orderMessageEmail.MessageChain = DbContext.Current
.Messages
.Where(c =>
c.OrderId == orderMessageEmail.OrderId &&
c.IsPublic &&
c.MessageId != orderMessageEmail.MessageId &&
c.MessageId < orderMessageEmail.MessageId
)
.OrderByDescending(c => c.MessageId)
.Take(10)
.Select(c => new {
c, u = c.User, cap = c.CustomerAccountPerson
}).
.AsEnumerable()
.Select(c => new OrderMessageChain()
{
CreateDateTime = c.c.CreateDateTime,
MessageId = c.c.MessageId,
Message = c.c.MessageData,
UserFirstName = c.u == null ? "" : c.u.FirstName,
UserLastName = c.u == null ? "" : c.u.LastName,
CustomerFirstName = c.cap == null ? "" : c.cap.FirstName,
CustomerLastName = c.cap == null ? "" : c.cap.LastName,
SentFrom = c.c.SentFrom
})
.ToList();
To one of my tables I added a sortOrder. I now need to update this query to respect the sortOrder authority!
Here is my current query:
var HTMLdocs = db.ProcedureDocs.Where(m => m.Procedures.Processes.processID == id && m.Document.html != null && m.Document.approvedBy != null).Select(m => m.Document);
The table that has sortOrder is Procedures.
How can I get the above query to return results that are ordered by sortOrder.
Here is the table structure.
Processes can have 0 or many Procedures.
Document can have 0 or many ProcedureDocs.
ProcedureDocs has a foreign key to Procedures on procedureid.
I somehow need to grab a collection of Document that somehow respects the order found in the Procedures table.
Let me know if you need any other information.
Try something like this:
var HTMLdocs = db.ProcedureDocs
.Where(m => m.Procedures.Processes.processID == id &&
m.Document.html != null &&
m.Document.approvedBy != null)
.OrderBy(m => m.Procedures.sortOrder)
.Select(m => m.Document);
Or in query syntax:
var HTMLdocs =
from m in db.ProcedureDocs
where m.Procedures.Processes.processID == id &&
m.Document.html != null &&
m.Document.approvedBy != null
orderby m.Procedures.sortOrder
select m.Document;
var HTMLdocs = db.ProcedureDocs
.Where(m => m.Procedures.Processes.processID == id
&& m.Document.html != null && m.Document.approvedBy != null)
.OrderBy(x=>x.Procedures.sortOrder)
.Select(m => m.Document)
How can you write this query using a lambda expression or LINQ:
SELECT *
FROM vehicles
WHERE (memo1 like '%CERTIFIED%' OR memo2 = 'CERTIFIED')
AND stockno IN (SELECT stockno FROM udealer2 where ACC='UCERT')
ORDER BY model, days DESC
Not knowing much about your model, here is a blind mechanical translation of your query:
vehicles.Where( v =>
(SqlMethods.Like(v.memo1, "%CERTIFIED%") || v.memo2 == "CERTIFIED") &&
udealer2.Any(d => d.ACC == "UCERT" && d.stockno == v.stockno)
).OrderBy(v => v.model)
.ThenByDescending(v => v.days)
where Dealers.Any(d => d.Account == "UCERT" && something.StockNo == d.StockNo)
I have the following code:
var columnNames = (from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
select GetDbColumnNames(autoExport.AutoExportTemplate, realName)).ToList();
Where the function GetDbColumns() returns an List<string>.
So columNames is of the type List<List<string>>.
Is it possible to create a List<string>, so each element of the list of GetDbColumns is added to the result of the LinQ query?
You can use the "select many" construction:
var columnNames = (
from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
from column in GetDbColumnNames(autoExport.AutoExportTemplate, realName)
select column).ToList();
Or here is an alternative way of using SelectMany:
var columnNames = (
from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
select autoExport
).SelectMany(x => x.GetDbColumnNames(autoExport.AutoExportTemplate, realName))
.ToList();
And finally, this is another way to put it (but it includes the somewhat ugly code x => x):
var columnNames = (
from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
select autoExport.GetDbColumnNames(autoExport.AutoExportTemplate, realName)
).SelectMany(x => x).ToList();