I have a 2 tables:
Activities ActivityKeywords
********** ****************
ID --> ActivityID
Name Keyword
I need to return all activities that match a specific keyword.
var q = from a in Context.Activities
where a.Keywords.Any(k => k.Keyword == someKeyword)
select a;
As I said in comments, it's nearly always wrong to use join in LINQ to Entities. The relationship properties should be used instead.
checkout the answer by Craig Stuntz for a cleaner way if you have a relation defined
My previous response was wrong but this works for me.
var activities = from a in db.Activities
join ak in db.ActivityKeywords on a.ID equals ak.ActivityID
where ak.Keyword == "yourkeyword"
select a;
I think you need something like
Give me all Activities which ID are in a list of ActivitiyKeywords.ID's
If that is your question, the you can try this:
var ids = from k in db.ActivityKeywords select k.ActivityID;
var result = from a in db.Activities where ids.Contains(a.ID) select a;
More information here.
var results = (from a in Activities
from k in ActivityKeywords
where k.Keyword == "keyword" && k.ActivityID == a.ID
select a).Distinct();
Related
There are three tables in the database that are relevant. Advocate, Vendor, and Advocate_Vendor.
The Advocate_Vendor table being the many to many link, has a vendorId and an advocateId.
My end goal is to get back a List<Advocate> object...a collection of advocates that belong to one Vendor. I wrote this:
var list = new List<Advocate>();
foreach (var vendorAdvocates in db.Advocate_Vendors)
{
if (vendorAdvocates.VendorId == vendorId)
{
list.Add(db.Advocates.SingleOrDefault(a => a.AdvocateId == vendorAdvocates.AdvocateId));
}
}
And then this:
var list = (from vendorAdvocates in db.Advocate_Vendors
where vendorAdvocates.VendorId == vendorId
select db.Advocates.SingleOrDefault(a =>
a.AdvocateId == vendorAdvocates.AdvocateId)).ToList();
Is this the best way? Seems wrong, like maybe there could be a more streamlined way to do this using a 'contains' keyword or something that looks a bit more readable...get all the vendor's advocates
thanks
Using a join between Advocate_Vendors and Advocates would be the right way of doing it.
var list = (from vendorAdvocates in db.Advocate_Vendors
join advocates in db.Advocates
on vendorAdvocates.AdvocateId equals advocates.AdvocateId
where vendorAdvocates.VendorId == vendorId
select advocates).ToList();
var list = (from vendorAdvocates in db.Advocate_Vendors
from advocate in db.Advocates
where vendorAdvocates.VendorId == vendorId &&
vendorAdvocates.AdvocateId = advocate.Id
select advocate)
.ToList();
If you set up your foreign keys and navigation properties properly, it should be possible to write this way, or something like it:
var list = (from vendorAdvocates in db.Advocate_Vendors
where vendorAdvocates.VendorId == vendorId
select db.Advocate).ToList();
I'm newbie to linq to sql, just trying to understand what type of queries I can handle with linq.
Here is my database scheme,
I want to get all customers of a specific user and this is what I've done,
var userId = 4;
var companies = from c in db.Company
where c.UserId == userId
select c.Id;
var costumers = from c in db.Customers
where companies.Contains(c.CompanyId)
select c;
I'm just wondering whether it's a nice approach and is there any better method to handle this type of queries?
Use can also get customers by this way also:
var result = db.Customers.Join(
db.Company, customer => customer.CompanyId, comp => comp.Id, (customer, comp)
=> new { customer, comp }).Where(#t => #t.comp.UserId == 4)
.Select(#t => #t.customer);
You can also keep it simple like this.
select * from db.Customers Cus
inner join db.company Com on Com.Id = Cus.CompanyId
where Com.UserId= userId
Contains is the equivalent of IN in SQL and your Linq statement will be translated to a SQL statement. So I can't really see another way that will give you better performance with Linq. If you want to use less code you can maybe try the following instead:
var companies = db.Companies.Where(x=> x.UserId == userid).Select(x=>x.Id);
var customers = db.Customers.Where(x=> companies.Contains(x.CompanyId));
I had tried to join two table conditionally but it is giving me syntax error. I tried to find solution in the net but i cannot find how to do conditional join with condition. The only other alternative is to get the value first from one table and make a query again.
I just want to confirm if there is any other way to do conditional join with linq.
Here is my code, I am trying to find all position that is equal or lower than me. Basically I want to get my peers and subordinates.
from e in entity.M_Employee
join p in entity.M_Position on e.PostionId >= p.PositionId
select p;
You can't do that with a LINQ joins - LINQ only supports equijoins. However, you can do this:
var query = from e in entity.M_Employee
from p in entity.M_Position
where e.PostionId >= p.PositionId
select p;
Or a slightly alternative but equivalent approach:
var query = entity.M_Employee
.SelectMany(e => entity.M_Position
.Where(p => e.PostionId >= p.PositionId));
Following:
from e in entity.M_Employee
from p in entity.M_Position.Where(p => e.PostionId >= p.PositionId)
select p;
will produce exactly the same SQL you are after (INNER JOIN Position P ON E..PostionId >= P.PositionId).
var currentDetails = from c in customers
group c by new { c.Name, c.Authed } into g
where g.Key.Authed == "True"
select g.OrderByDescending(t => t.EffectiveDate).First();
var currentAndUnauthorised = (from c in customers
join cd in currentDetails
on c.Name equals cd.Name
where c.EffectiveDate >= cd.EffectiveDate
select c).OrderBy(o => o.CoverId).ThenBy(o => o.EffectiveDate);
If you have a table of historic detail changes including authorisation status and effective date. The first query finds each customers current details and the second query adds all subsequent unauthorised detail changes in the table.
Hope this is helpful as it took me some time and help to get too.
having some problems figuring this one out.
select *,(select top 1 chicken_nr from chicken_photo where chicken = code order by [sort]) as Photo from Chicken
Code is a column in Table Chicken
Basically getting the cover photo for this chicken.
To make it clearer, I want it to return multiple rows from table Chicken. But only a single entry from chicken_photo.
var q = from chicken in data.chickens
join photos in data.chicken_photos
on chicken.Code equals photos.chicken
where chicken.Lang==lang && chicken.photographer_nr == nr
group chicken by new {chicken.photographer,photos.Photograph_Nr,chicken.Title,chicken.Code}
This can indeed be done such that it results in only one SQL query underneath.
If you perform the subselect as you have written against Entity Framework, then the Linq query will become a single SQL query.
var q = from chicken in data.chickens
where chicken.photographer_nr == nr && chicken.Lang == lang
select new
{
chicken.photographer,
chicken.Code,
chicken.Title,
Photo = (from cp in data.chicken_photos
where cp.chicken == chicken.Code
orderby cp.Sort
select cp.Photograph_Nr).FirstOrDefault()
};
If your tables have proper primary and foreign key relationships, and proper navigation associations in Entity Framework then you can also achieve the same results this way:
var q = from chicken in data.chickens
where chicken.photographer_nr == nr && chicken.Lang == lang
select new
{
chicken.photographer,
chicken.Code,
chicken.Title,
Photo = c.chicken_photos.Select(cp => cp.Photograph_Nr).FirstOrDefault()
};
And finally, to stay completely consistent and use only lambda-expressions:
var q = data.chickens
.Where(c => chicken.photographer_nr == nr && chicken.Lang == lang)
.Select(c => new
{
c.photographer,
c.Code,
c.Title,
Photo = c.chicken_photos.Select(cp => cp.Photograph_Nr).FirstOrDefault()
}
);
I prefer relying on entity navigation, as it forces the developer to create proper navigation associations in Entity Framework and proper foreign key relationships in the database. This will almost always result in optimized SQL underneath.
It's not always up to the developer how the database is structured, so you may have to stick with the first approach and write the sub-select yourself.
I figured it out.
Pretty obvious actually, too obvious :)
var q = from chicken in data.chickens
where chicken.photographer_nr == nr && lang == chicken.Lang
select new { chicken.photographer, chicken.Code, chicken.Title,Photo = (from b in data.chicken_photos where b.chicken==chicken.Code orderby b.Sort select b.Photograph_Nr).FirstOrDefault() };
var photo = (from c in chicken_photo where c.code = chicken orderby c.sort select c.chicken_nr).Take(1).SingleOrDefault();
You should really flesh out your question more...
Here's an example of the query I'm trying to convert to LINQ:
SELECT *
FROM Users
WHERE Users.lastname LIKE '%fra%'
AND Users.Id IN (
SELECT UserId
FROM CompanyRolesToUsers
WHERE CompanyRoleId in (2,3,4) )
There is a FK relationship between CompanyRolesToUsers and Users, but it's a many to many relationship and CompanyRolesToUsers is the junction table.
We already have most of our site built, and we already have most of the filtering working by building Expressions using a PredicateExtensions class.
The code for the straightforward filters looks something like this:
if (!string.IsNullOrEmpty(TextBoxLastName.Text))
{
predicateAnd = predicateAnd.And(c => c.LastName.Contains(
TextBoxLastName.Text.Trim()));
}
e.Result = context.Users.Where(predicateAnd);
I'm trying to add a predicate for a subselect in another table. (CompanyRolesToUsers)
What I'd like to be able to add is something that does this:
int[] selectedRoles = GetSelectedRoles();
if( selectedRoles.Length > 0 )
{
//somehow only select the userid from here ???:
var subquery = from u in CompanyRolesToUsers
where u.RoleID in selectedRoles
select u.UserId;
//somehow transform this into an Expression ???:
var subExpression = Expression.Invoke(subquery);
//and add it on to the existing expressions ???:
predicateAnd = predicateAnd.And(subExpression);
}
Is there any way to do this? It's frustrating because I can write the stored procedure easily, but I'm new to this LINQ thing and I have a deadline. I haven't been able to find an example that matches up, but I'm sure it's there somewhere.
Here's a subquery for you!
List<int> IdsToFind = new List<int>() {2, 3, 4};
db.Users
.Where(u => SqlMethods.Like(u.LastName, "%fra%"))
.Where(u =>
db.CompanyRolesToUsers
.Where(crtu => IdsToFind.Contains(crtu.CompanyRoleId))
.Select(crtu => crtu.UserId)
.Contains(u.Id)
)
Regarding this portion of the question:
predicateAnd = predicateAnd.And(c => c.LastName.Contains(
TextBoxLastName.Text.Trim()));
I strongly recommend extracting the string from the textbox before authoring the query.
string searchString = TextBoxLastName.Text.Trim();
predicateAnd = predicateAnd.And(c => c.LastName.Contains( searchString));
You want to maintain good control over what gets sent to the database. In the original code, one possible reading is that an untrimmed string gets sent into the database for trimming - which is not good work for the database to be doing.
There is no subquery needed with this statement, which is better written as
select u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
or
select u.*
from Users u inner join CompanyRolesToUsers c
on u.Id = c.UserId --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
That being said, in LINQ it would be
from u in Users
from c in CompanyRolesToUsers
where u.Id == c.UserId &&
u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
or
from u in Users
join c in CompanyRolesToUsers
on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is...
This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.
from u in Users
join c in (
from crt in CompanyRolesToUsers
where CompanyRoleId == 2
|| CompanyRoleId == 3
|| CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;
You could do something like this for your case - (syntax may be a bit off). Also look at this link
subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();
finalQuery = from u in Users where u.LastName.Contains('fra') && subQuery.Contains(u.Id) select u;
Ok, here's a basic join query that gets the correct records:
int[] selectedRolesArr = GetSelectedRoles();
if( selectedRolesArr != null && selectedRolesArr.Length > 0 )
{
//this join version requires the use of distinct to prevent muliple records
//being returned for users with more than one company role.
IQueryable retVal = (from u in context.Users
join c in context.CompanyRolesToUsers
on u.Id equals c.UserId
where u.LastName.Contains( "fra" ) &&
selectedRolesArr.Contains( c.CompanyRoleId )
select u).Distinct();
}
But here's the code that most easily integrates with the algorithm that we already had in place:
int[] selectedRolesArr = GetSelectedRoles();
if ( useAnd )
{
predicateAnd = predicateAnd.And( u => (from c in context.CompanyRolesToUsers
where selectedRolesArr.Contains(c.CompanyRoleId)
select c.UserId).Contains(u.Id));
}
else
{
predicateOr = predicateOr.Or( u => (from c in context.CompanyRolesToUsers
where selectedRolesArr.Contains(c.CompanyRoleId)
select c.UserId).Contains(u.Id) );
}
which is thanks to a poster at the LINQtoSQL forum
Here's a version of the SQL that returns the correct records:
select distinct u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.firstname like '%amy%'
and c.CompanyRoleId in (2,3,4)
Also, note that (2,3,4) is a list selected from a checkbox list by the web app user, and I forgot to mention that I just hardcoded that for simplicity. Really it's an array of CompanyRoleId values, so it could be (1) or (2,5) or (1,2,3,4,6,7,99).
Also the other thing that I should specify more clearly, is that the PredicateExtensions are used to dynamically add predicate clauses to the Where for the query, depending on which form fields the web app user has filled in. So the tricky part for me is how to transform the working query into a LINQ Expression that I can attach to the dynamic list of expressions.
I'll give some of the sample LINQ queries a shot and see if I can integrate them with our code, and then get post my results. Thanks!
marcel