views:

60

answers:

2
public List<string> TagNameList (int objectId)
{
    List<string> tagNameList = db.Tags.Where(ob => ob.Id == objectId).ToList();  
}

db.Tags.Where(ob => ob.Id == objectId).ToList(); 

I'm going into the db context in the Tags and i select all the tags that have a set objectId via a navigation property i have setup through an ObjectTags table that stores the relationships in two columns, both make up a composite key.

The sample returns an IQueryable<app.Models.Tag>. Is there any quick way to convert this to a List<string> with just the Tag.Name?

+5  A: 

Yup, you just need to apply a projection using Select:

public List<string> TagNameList (int objectId)
{
    return db.Tags.Where(ob => ob.Id == objectId)
                  .Select(tag => tag.Name)
                  .ToList();  
}

EDIT: Okay, given your update, you can use First() if you only want the first object from each collection - if you want the name from each object in the collection, you could use SelectMany:

public List<string> TagNameList (int objectId)
{
    return db.Tags.Where(ob => ob.Id == objectId)
                  .SelectMany(ob => ob.Tags)
                  .Select(tag => tag.Name)
                  .ToList();  
}
Jon Skeet
YES. Perfect! :)
basilmir
Not so fast... :) I have a relationships table with multiple ObjectIds and multiple TagIds. I can't access the relationships table directly, since it does not appear in ADO.net. I can only access it via the Objects table. Something like this db.Objects.Where(ob => ob.Id == objectId).Select(t => t.Tags) I am going into the Objects table and narrowing it down, then selecting stuff in the Tags table. Now i have a bunch of EntityCollection<Models.Tags>. How do i convert these to a list or something usable in the model i pass to the view?
basilmir
Edited with more information: I have a relationships table with multiple ObjectIds and multiple TagIds. I can't access the relationships table directly, since it does not appear in ADO.net. I can only access it via the Objects table. Something like this db.Objects.Where(ob => ob.Id == objectId).Select(t => t.Tags) I am going into the Objects table and narrowing it down, then selecting stuff in the Tags table. Now i have a bunch of ...IQueryable<...DataClasses.EntityCollection<Models.Tags>. How do i convert these to a list or something usable in the model i pass to the view?
basilmir
A: 

Found the solution thanks to a good friend.

db.Objects.Where(ob => ob.Id == objectId).First().Tags.Select(t => t.TagName).ToList()

The First() was essential to "narrow" it down to one object and then navigate to the other table.

This is SO COOL. You could navigate to tens of tables like this. I wonder if you can write the longest line of code this way :D

basilmir