Help with Linq to Entities query
I am trying to increase my knowledge of linq so I would like to create the following query without using a stored procedure but I am no开发者_如何学Got really sure how to structure it.
If I have three table/entities:
Farmer (FarmerId, BusinessTitle)
Produce (ProduceId, ProduceTitle)
FarmerProduce (FarmerId, ProduceId)
How would I do a query that searched the BusinessTitle & ProduceTitle for a particular word (say Raspberry) and returned a list of Farmer entities.
I can achieve a search on either Farmer of Produce separately e.g.:
var query = (from f in farmer
where f.BusinessTitle.Contains("raspberry")
select l).ToList();
var query = (from fp in FarmerProduce
where fp.Produce.ProduceTitle.Contains("raspberry")
select fp.Farmer).ToList();
But I am unsure how to combine the FarmerProduce "lookup table" into a single query.
This one should be a simple OR in linq by the looks of it.
var query = (from fp in FarmerProduce
where fp.Produce.ProduceTitle.Contains("raspberry")
|| fp.Farmer.BusinessTitle.Contains("raspberry")
select fp.Farmer).Distinct().ToList();
Added Distinct.
If you only need the farmers:
var query = from f in farmer
where f.BusinessTitle.Contains("raspberry")
|| f.Produces.Any(p => p.ProduceTitle.Contains("raspberry"))
select f;
Assuming the many-to-many was inported as a Produces
navigation property.
精彩评论