tags:

views:

3881

answers:

3

Hi,

I have a table that I need to extract data from, and wish to discard one of the two columns that the data comes from. In my DB, I have "ObjectID (PK)" and "ObjectName".

I wish to use this data to populate a SelectList in an ASP.NET MVC project, and so have an IQueryable object in my code which looks as follows:

public IQueryable<objectRef> FindSomeObject()
{
    return from myObj in db.TableName
        orderby myObj.colName
        select myObj;
}

If I attempt to change the last line to pull only a single column worth of data, such as:

select new { myObject.colName };

I get a warning that I am attempting to implicitly convert an anonymous type to my current type.

The annoyance is that this query gets used in ViewData[""] to set a SelectList, which displays the drop down fine, but writes the PK value to the new table instead of the text.

I'm assuming that I know so little about this that I cannot even ask Google the right question, as hours of RTFM have revealed nothing useful. Any help would be appreciated.

+6  A: 

You need to change the return type of your method - if you only want to select one column, just declare that you're going to return something of that column. For example:

public IQueryable<string> FindSomeObject()
{
    return from myObj in db.TableName
        orderby myObj.colName
        select myObj.colName;
}

That basically says it's a query which returns a sequence of strings - which is what you want, I assume.

Jon Skeet
+3  A: 

Use the type of colName, like:

public IQueryable<string> FindSomeObject()
{
    return from myObj in db.TableName
        orderby myObj.colName
        select myObj.colName;
}
eglasius
+1  A: 

Did you try:

public IQueryable<objectRef> FindSomeObject()  
{
    return from myObj in db.TableName
        orderby myObj.colName
        select myObj.colName;
}

And by the way, do you have a class called objectRef, starting lowercase? That ought to have an uppercase letter at the start (and it needs to be whatever type colName is).

Daniel Earwicker
@Jon Skeet, Freddy Rios and EarwickerThanks for the replies, and for pointing me in the right direction. Everything is working as expected.@Earwicker: my actual code is better than my provided example. I still find myself punching out Perl-style syntax a lot ;)
Paul Stevens