IN Operator in where clause - c#

List<HelprClass.Organizer> org =
( from EventOrg in cntx.EventOrganizer
from MstrOrg in cntx.Organizer
where EventOrg.OrganizerID == MstrOrg.OrganizerID
Select new HelprClass.Organizer
{
OrganizerName = MstrOrg.OrganizerName
}).ToList()
This work fine now i want to use IN Opeartor in the above Query.
in the EventOrganizer I have EventID now i want to select only Event ID exsist in EventOrganizer collection
I have EventID another var varibale
Var EventID= From EvntID in Evetn Select new {ID= EvntID.EventID};
Something like this
where
EventOrg.OrganizerID == MstrOrg.OrganizerID
&& EventOrg.EventID in EventID.ID
How I can achive this ?
I will appreciate your help

Try this:
var EventIDs = from EvntID in Event select EvntID.EventID;
var org = (from EventOrg in cntx.EventOrganizer
from MstrOrg in cntx.Organizer
where EventOrg.OrganizerID == MstrOrg.OrganizerID
select new {E=EventOrg, M=MstrOrg}
).ToList();
org = org
.Where(o => EventIDs.Contains(o.E.EventID) )
.Select(o => new HelprClass.Organizer
{
OrganizerName = o.M.OrganizerName
}
);

If you are using Entity Framework you can not use a Contains statement, which would be an easy solution in Linq. SO if it's just Linq 2 Entities, use a where clause like "where EventId.Contains(EventOrg.Id)"
If you are indeed using Entity Framework you will have to build an or expression based on the Id's in the EventID Collection.

Related

Write query in Entity Framework

I have a query which I ran successfully in SQL Server Management Studio, which returns the table values shown in the screenshot
The query I used is:
SELECT tcoid, COUNT(*) ownleasetank
FROM TankProfile
WHERE ownleasetank = 3
GROUP BY tcoid
Now I'm using Entity Framework to make things easier in my sample project.
I used this method to return the table values as array object:
public async Task<Object> GetLeaseInformationPrincipal()
{
ISOTMSEntities context = new ISOTMSEntities();
var testleaseinfo = from d in context.TankProfiles
join f in context.TankOperators
on d.tcoid equals f.tcoId
where (d.ownleasetank == 3)
select new { f.tcoName, d.ownleasetank } into x
group x by new { x.tcoName } into g
select new
{
tconame = g.Key.tcoName,
ownleasetank = g.Select(x => x.ownleasetank).Count()
};
return testleaseinfo.ToList();
}
but it is not working properly. I also tried other ways, when I use where and groupby method in Entity Framework it doesn't working properly for me.
Does anybody know the solution for this?
It's very simple with LINQ methods:
context.TankProfiles
.Where(t => t.ownleasetank = 3)
.GroupBy(t => t.tcoid)
.Select(g => new {g.Key, g.Count()})
.ToArray();
I have no idea why in your C# version of the query you have such opeartions such join, while your SQL query is very simple. You have to rethink that :)
var c = from t in context.TankProfile
where t.ownleasetank == 3
group t by t.tcoid into g
select new { tcoid=g.Key, ownleasetank=g.Select(x => x.ownleasetank).Count() };
return c.ToList();

Get object by ID eg SQL WHERE predicate in Entity Framework

I had a look at Entity Framework, get object by ID.
I can't get that to work.
I specifically want the
WHERE [Extent1].[CatId] = 1
as I don't want to return everything that filter it as in
using (ApplicationContext db = new ApplicationContext())
{
IQueryable<Project> projects = db.Projects; // Get all
var p = (from i in db.Projects where i.Id == ProjectID select i);
Console.WriteLine("Project # {0} added and Named:{1} ", ProjectID, p.First().Name);
Assert.IsNotNull(projects.First().Name);
}
So what I am looking for in SQL terms is
SELECT *
FROM Projects
WHERE id = 1
Hope that makes sense.
You should be able to use LINQ fluent syntax:
var project = db.Projects.SingleOrDefault(i => i.Id == ProjectId);
Great LINQ reference and examples

Building a custom|progressive query in LINQ?

I have a page with five text boxes, each one representing a field in my database table and a search button:
If I were using SQL I could build my SQL statement depending on which fields have data in them.
However, I want to use LINQ, and I'm at a loss as to how to accomplish this. For instance, take a look at the query below:
var db = new BookDBDataContext();
var q =
from a in db.Books
where a.Title.Contains(txtBookTitle) &&
a.Author.Contains(txtAuthor) &&
a.Publisher.Contains(txtPublisher)
select a.ID;
The query above will return data where all the fields match data in the table. But, what if the user didn't enter an Author in the txtAuthor field? If I were building this as a query string, I could check each field for data and add it to the query string. Since this is LINQ, I can't dynamically change the search criteria, it seems.
Any advice would be greatly appreciated!
var db = new BookDBDataContext();
var q = (from a in db.Books
where a.Title.Contains(txtBookTitle));
if(!String.IsNullOrEmpty(txtAuthor))
{
q = q.Where(a => a.Author.Contains(txtAuthor));
}
if(!String.IsNullOrEmpty(txtAuthor))
{
q = q.Where(a => a.Publisher.Contains(txtPublisher));
}
var id = q.Select(a => a.ID);
from a in db.Books
where (string.isNullorWhiteSpace(search) || a.Title.Contains(search)) &&
(string.isNullorWhiteSpace(txtAuthor) || a.Author.Contains(txtAuthor) ) &&
(string.isNullorWhiteSpace(txtPublisher) || a.Publisher.Contains(txtPublisher))
select a.ID;

FIiter Out the Linq Query

I have List List courseTakenList.i want to filter out the Status which are in Completed,Dropped,Current,Schudeled. Here is the code sample.
courseTakenList = (from courseTaken in courseTakenList
select new Course
{
Status = "Scheduled"?"COMPLETE"?"Dropped"? "Current"
}).ToList();
You could do it even more concise
var statuslist= {"Completed","Dropped","Current","Schudeled"};
var courses = courseTakenList.Where(courseTaken =>
statuslist.Contains(courseTaken.Status);
Linq In query like this will resolve your issue
var statuslist= {"Completed","Dropped","Current","Schudeled"};
var query = from courseTaken in courseTakenList
where statuslist.Contains( courseTaken .Status )
select courseTaken ;
Note : change select clause as you want

Entity Framework select distinct name

How can I do this SQL query with Entity Framework?
SELECT DISTINCT NAME FROM TestAddresses
Using lambda expression..
var result = EFContext.TestAddresses.Select(m => m.Name).Distinct();
Another variation using where,
var result = EFContext.TestAddresses
.Where(a => a.age > 10)//if you have any condition
.Select(m => m.name).Distinct();
Another variation using sql like syntax
var result = (from recordset
in EFContext.TestAddresses
.where(a => a.city = 'NY')//if you have any condition
.select new
{
recordset.name
}).Distinct();
Try this:
var results = (from ta in context.TestAddresses
select ta.Name).Distinct();
This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.
The way that #alliswell showed is completely valid, and there's another way! :)
var result = EFContext.TestAddresses
.GroupBy(ta => ta.Name)
.Select(ta => ta.Key);
I hope it'll be useful to someone.
DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you
Entity-Framework Select Distinct Name:
Suppose if you are using Views in which you are using multiple tables and you want to apply distinct in that case first you have to store value in variable & then you can apply Distinct on that variable like this one....
public List<Item_Img_Sal_VIEW> GetItemDescription(int ItemNo)
{
var Result= db.Item_Img_Sal_VIEW.Where(p => p.ItemID == ItemNo).ToList();
return Result.Distinct().ToList();
}
Or you can try this Simple Example
Public Function GetUniqueLocation() As List(Of Integer)
Return db.LoginUsers.Select(Function(p) p.LocID).Distinct().ToList()
End Function
use Select().Distinct()
for example
DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();
In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT error, the best should be
var results = (
from ta in DBContext.TestAddresses
select ta.Name
)
.Distinct()
.OrderBy( x => 1);
Entity-Framework Select Distinct Name:
Suppose if you are want every first data of particular column of each group ;
var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();
foreach (var item in data)
{
var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();
//Eg.
{
ListBox1.Items.Add(data2.ColumnName);
}
}

Categories

Resources