2

I have an INT fields called TradeNo that may contain NULL value. The requirement is to display on the dropdown the "contract Id" and the "trade no" in bracket and if "trade no" is null, then display N/A.

Example:
44444 (2222)
55555 ( N/A )

Here’s what I thought would work. This is my functions that returns a SelectList

public IEnumerable<SelectListItem> GetContractsBySupplierDropDown(string supplier)
{
    var result = from c in context.Contracts 
                     where c.Supplier==supplier 
                     orderby c.ContractID
                     select new { 
                            Text = c.ContractID.ToString() + " (" + 
                                   (c.TradeNo.HasValue  ? 
                                       c.TradeNo.Value.ToString() : 
                                       " N/A ").ToString() + 
                                    " )", 
                            Value = c.ContractID };

    return new SelectList(result, "Text", "Value"); 
}

The error being return is:

LINQ to Entities does not recognize the method 'System.String ToString()'
method, and this method cannot be translated into a store expression.

From what I can tell, the error displayed means that EF is trying to convert ToString to a database function?

1 Answer 1

2

Unfortunately you cannot use ToString in a number field coming from the database.

As a work around you can cast ToList before doing it, so then the contents are in the memory.

public IEnumerable<SelectListItem> GetContractsBySupplierDropDown(string supplier)
{
    var query =  from c in context.Contracts 
                 where c.Supplier==supplier 
                 orderby c.ContractID
                 select new {
                     c.ContractID,
                     c.TradeNo,

                 };
    var result = from c in query.ToList()
                 select new { 
                            Text = c.ContractID.ToString() + " (" + 
                                   (c.TradeNo.HasValue  ?
                                       c.TradeNo.Value.ToString() : 
                                       " N/A ") + 
                                    " )", 
                            Value = c.ContractID
                  };

    return new SelectList(result, "Text", "Value");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.