Saturday, July 31, 2010

LINQ Join in Entity Framework 4

I want to explain a simple linq join in entity framework 4.

Example 1:

I have 3 tables in my database:
Tables:
------------
Tags (TagID, TagName)
Contents (ContentID, TagID)
ContentTags (ContentID, TagID)

This is the method to return all the tag entities related to a particular content.

public List<TagEntity> GetContentTags(int contentID)
{
   IObjectSet<TagEntity> objSetTags =   base._objectContext.CreateObjectSet<TagEntity>();
   IObjectSet<ContentTagDTO> objSetContentTags = base._objectContext.CreateObjectSet<ContentTagDTO>();
var query =
  from tag in objSetTags
  join contentTag in objSetContentTags
  on tag.TagID equals contentTag.TagID
  where contentTag.ContentID == contentID
  select tag;
 
  List<TagEntity> tags = query.ToList();
  return tags;
}

Example 2:

using EF4.1 and DbContext,
Tables:
------------
Contents(ContentID, PublishedVersion, CatalogID)
Versions(ContentID, Version, Body)

// it selects top 20
var query = (from c in context.Contents
             join v in context.Versions
             on new { contentID = c.ContentId, version = c.PublishedVersion }
             equals new { contentID = v.ContentID, version = v.Version }
             where
             c.PublishedVersion != null
             select new
             {
                ContentID = v.ContentId,
                Body = v.Body,
                CatalogId = c.CatalogId
             }).Take(20);

string sql = query.ToString();


Cheers mate!

0 comments:

Post a Comment