GPGVM
GPGVM

Reputation: 5619

Resolve Linq join from Id to value

I'm trying to figure out how to get the results to show the name value instead of the id value on a join of two tables. My tables basically look like this:

VideoCatwegories (table name) Id, CategoryName

and

Videos (table name) Id, VideoCategory (fk to category table) Title Desc Url

My linq join:

var query = _videoRepository.Table
.Join
(
    _videoCategoryRepository.Table,
    v => v.Id,
    vc => vc.Id,
    (v, vc) => new { Videos = v, VideoCategories = vc }
)
.Select(vid => vid.Videos);

The results yield the category id of 1 instead of Instructional etc.

What am I not understanding / doing correctly?

Thank You

Upvotes: 1

Views: 134

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

First, your join criterion does not look right: it appears that you are joining an id of video to the id of video category, which is probably not set up that way: more likely, video has an id of the corresponding video category, in which case you should use that id in the join.

The rest of your join appear to be fine. The problem is that you are projecting out the results of the join in the Select method. You should remove it, and use the anonymous class to get the data that you need from the joined category, like this:

var query = _videoRepository.Table.Join(
    _videoCategoryRepository.Table
,   v => v.CategoryId // <<== Use the proper ID here
,   vc => vc.Id
,   (v, vc) => new { Videos = v, VideoCategories = vc } // <<== This part is fine
);
foreach (var v in query) {
    Console.WriteLine("Video: '{0}'
    ,   category '{1}'"
    ,   v.Videos.Name
    ,   v.VideoCategories.Name
    );
}

Upvotes: 1

Konstantin
Konstantin

Reputation: 3294

var query = 
       (from v in _videoRepository
        from c in _videoCategoryRepository
        where c.Id == v.Id
        select new { id = v.id, catname = c.CategoryName, vname = v.Title }
        ).ToList()

Upvotes: 1

Related Questions