Entity Framework 4.1 Link table query how to? - linq

I'm relatively new to the Entity Framework and I'd like to do a query that includes a link table. Any suggestions on how to do a basic join query using LINQ?
Entity Structure
News
NewsID
CommunityNews
CommunityID
NewsID
Community
CommunityID

If you're generating the context from a database using the EDMX editor, and you have the appropriate foreign key constraints set up, you should be able to just add those three tables to the context, and it will create a many-to-many mapping between News and Community.
var newsForCommunity = context.News.Where(
n => n.Communities.Any(
c => c.CommunityId == communityId);

Here is another way you can write the query:
var newsForCommunity =
(from c in context.Communities
from n in c.News
where c.CommunityID == communityID
select n.NewsID
).ToList();

Related

How to work with Aggregate function in LINQ with join

Need help in LINQ expression,
I have 2 tables Article and comments foreign key is Article_id .Now i need data using both the tables using linq to sql like article_id,Article_title,Total_Comments(Count of comments on current article article),
tale Structure :
table 1(Article) : Article_ID,Article_Title.. etc
table 2(comments ): Comment_auto_id,Comment_text,Comment_by(User_ID),Article_ID
something like that ?
from article in Articles
join comment in Comments on article.Article_ID equals comment.ArticleID into articleComments
select new {
Article = article,//or more detailed if you want only part of Articles entity
Total_Comments = articleComments.Count()
}
Maybe you need to use .GroupJoin() extension method.
Source: http://msdn.microsoft.com/en-us/library/system.linq.enumerable.groupjoin.aspx

JOINING a ActivityParty Field

I am trying to query data in CRM 2011 and I need to join an ActivityParty. I can't seem to find any good documentation on it. Has anyone done this before. This is my query so far:
var linqQuery = (from r in gServiceContext.CreateQuery("campaignresponse")
join c in gServiceContext.CreateQuery("contact") on ((EntityReference)r["customer"]).Id equals c["contactid"] into opp
join a in gServiceContext,CreateQuery("lead") on ((EntityReference)r["customer"]).Id equals c["leadid"] into opp
from o in opp.DefaultIfEmpty()
where ((EntityReference)r["new_distributorid"]).Id.Equals(lProfileProperty.PropertyValue) && ((OptionSetValue)r["new_distributorstatus"]).Equals("100000002")
select new
{ }
So if you look at the query what I am trying to do is join the contact Entity and the lead Entity to CamapaignResponse via the customer field and the customer field is an ActivityParty field. Any ideas on how to do this? Thanks!
I'm having a hard time figuring out how your query is supposed to work, but I can tell you that you'll have an easier time if you generate Linq entities using the SDK. Then, instead of
from r in gServiceContext.CreateQuery("campaignresponse") where ...
you can just write
gServiceContext.CampaignResponseSet
.Where(cr => cr.property == value)
.Select(cr => new {cr, cr.childObject});
and so forth. You'll get strong typing and IntelliSense, too.

linq with Include and criteria

How would I translate this into LINQ?
Say I have A parent table (Say, customers), and child (addresses).
I want to return all of the Parents who have addresses in California, and just the california address. (but I want to do it in LINQ and get an object graph of Entity objects)
Here's the old fashioned way:
SELECT c.blah, a.blah
FROM Customer c
INNER JOIN Address a on c.CustomerId = a.CustomerId
where a.State = 'CA'
The problem I'm having with LINQ is that i need an object graph of concrete Entity types (and it can't be lazy loaded.
Here's what I've tried so far:
Edit: added context instantiation as requested
// this one doesn't filter the addresses -- I get the right customers, but I get all of their addresses, and not just the CA address object.
var ctx = new CustomersContext() // dbContext -- using EF 4.1
from c in ctx.Customer.Include(c => c.Addresses)
where c.Addresses.Any(a => a.State == "CA")
select c
// this one seems to work, but the Addresses collection on Customers is always null
var ctx = new CustomersContext() // dbContext -- using EF 4.1
from c in ctx.Customer.Include(c => c.Addresses)
from a in c.Addresses
where a.State == "CA"
select c;
Any ideas?
Based on the code above, it appears that you already have a rehydrated collection of Customer objects in the Customer variable.
You will need to call the Include function when you fill your Customer collection above. This way, the framework will rehydrate the included objects at the time of retrieval from your data context.
The actual query code appears good though.

EF 4 LINQ Expression load items based on related entity

Here is the expression
x => x.stf_Category.CategoryID == categoryId
x refers to an Product Entity that contains a Category. I am trying to load all Products that match given categoryId.
In the db the Product table contains a Foreign Key reference to Category (via CategoryId).
Question: I think I am doing it wrong. Is there something else one has to do in EF4 to create a LINQ expression of this type?
Are there any good examples of EF4 Linq expressions out there? Specifically something that queries on the basis of related entities such as my problem ?
Thanks !
You're looking for the Include method.
var query = db.Products.Include("Categories");
This is commonly referred to as eager loading.
Entity Framework will 'infer' the JOIN constraint based on the mapping you have specified.
The "magic string" needs to match the Entity Set name on your EDMX.
Check out this post for more info.
EDIT
I'm a little confused as to whether you want the Products and Categories, or just the Products which have a specific Category ID.
If the latter, this is the way to go:
var query = from p in db.products
join c in db.categories
on p.CategoryId equals c.CategoryId
where c.CategoryId == someCategoryId
select p;
Keep in mind though, the above query is exactly the same result as your original query.
If p is a product, then p.Categories will look at the Navigational Property of your Product entity on the EDMX, in which case it will be your Category FK.
As long as you setup your Navigational properties right, p.Categories is fine.
If you are using EF4 and the association between Category and Product classes has been picked up and defined in your Model, then all products with a specific categoryID can be selected as simple as:
x => x.CategoryID == categoryID
You don't need to join nor an eager loading for that.

Insert to 2 tables in single query using LINQ

I need to insert to two tables in a single query. Is this possible to do in LINQ?
At present I am using insertonsubmit() 2 times.
If your tables have a primary key/foreign key relationship to each other, then you also have two objects which you can link to each other:
InternetStoreDataContext db = new InternetStoreDataContext();
Category c = new Category();
c.name = "Accessories";
Product p = new Product();
p.name = "USB Mouse";
c.Products.Add(p);
//and finally
db.Categories.Add(c);
db.SubmitChanges();
That adds your object and all linked objects when submitting the changes.
Note that for that to work, you must have a primary key in both tables. Otherwise LINQ doesn't offer you the linking possibility.
Here are good examples of using LINQ to SQL: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
The database submit doesn't happen until you call SubmitChanges. There is no tangible cost associated with multiple calls to InsertOnSubmit - so why not just do that?
This will still result in two TSQL INSERT commands - it simply isn't possible to insert into two tables in a single regular INSERT command.

Resources