Vince
Vince

Reputation: 615

Linq to Entities Join -- I don't want anonymous types

I have two tables that are related via a mapping table:

  1. keywords
  2. titles

I am trying to return a list of Map_Keywords_Title (the mapping table's object) based on the results of a join.

Until I added the last part with typedQuery it was just returning objects of anonymous type. I want it to return items of type Map_Keywords_Title so I tried adding the Select at the end (also tried Cast but that failed). The problem now is that the resulting objects are not managed by entity framework so I can't save changes to them.

Is there no straightforward way to do this in Linq to Entities? I'm using VS2008 so I don't yet have the new EF.

    public IList<Map_Keywords_Title> MatchingTitleKeywordMappings(string containedInText)
    {
        var keywords = QueryKeywords();
        if (!string.IsNullOrEmpty(containedInText))
        {
            Expression<Func<Keyword, bool>> exprContainsKeyword = k => containedInText.Contains(k.WordText);
            keywords = keywords.Where(exprContainsKeyword);
        }
        var maps = QueryMap_Keywords_Title();
        var anonQuery = keywords.Join(
            maps,
            key => (int)key.Id,
            map => (int)map.Keyword.Id,
            (key, map) => new
            {
                map.Id,
                map.Keyword,
                map.Title
            });
        var typedQuery = anonQuery.ToList().Select(anon => new Map_Keywords_Title()
            {
                Id = anon.Id,
                Keyword=anon.Keyword,
                Title=anon.Title
            });

        return typedQuery.ToList();
    }

Upvotes: 1

Views: 1876

Answers (1)

kervin
kervin

Reputation: 11858

Ok, I got tired of comments...

using( someContext sc = new someContext())
{
    sc.Map_Keywords_Title.Include("Title")
                .Include("Keyword")
                .Where( mkt => containedInText.Contains(mkt.Keyword.WordText));
}

Is that anywhere close to what you want?

Upvotes: 3

Related Questions