简体   繁体   中英

When converting month number to string error : Does not recognize the method 'System.String ToString(Int32)'

trying to select disctinct months in number form from db where there is a record of that month on database.

        public IEnumerable<months> dropdownMonths(datafilter dataparams)
    {
        try
        {
            var _dbEntity = new VXI_GLOBALiTRACKEntities();
            var unique_months =
                _dbEntity
                    .TBL_REQUEST
                    .Select(s => new months
                    {
                        value = s.REQUEST_DATE_SUBMITTED.Value.Month,
                        yr = s.REQUEST_DATE_SUBMITTED.Value.Year,
                        month = Convert.ToString(s.REQUEST_DATE_SUBMITTED.Value.Month)

                    })
                    .Distinct()
                    .Where(s => s.yr == dataparams.year)
                    .ToList();

            return unique_months;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

now on month = Convert.ToString(s.REQUEST_DATE_SUBMITTED.Value.Month)

it gets the error

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

how can i fix this or how can i convert the number of that month into month string eg {value: 1, month: JAN}

Check your RDBMS version and EF version,do they support DATEPART method

eg

sqlserver 2017 have a table like below

CREATE TABLE [Table1](
    [col_datetime] [datetime] NULL
);

insert into [Table1] 
select '2019/01/02 03:04:05'

then ef query

Table1s.Select(w => new { month = Convert.ToString(w.Col_datetime.Value.Month)})

it'll query below sql

SELECT CONVERT(NVarChar,DATEPART(Month, [t0].[col_datetime])) AS [month]
FROM [Table1] AS [t0]

if it not support then it'll get error LINQ to Entities does not recognize the method 'System.String ToString(Int32)' method, and this method cannot be translated into a store expression.

if you must to do it without support function,you can ToList() save data to memory first then select

Table1s.Where(w=>/*your filter logic*/).ToList().Select(w => new { month = Convert.ToString(w.Col_datetime.Value.Month)})

If REQUEST_DATE_SUBMITTED is of type DateTime in your entity then

month = s.REQUEST_DATE_SUBMITTED.ToString().Substring(0, 3).ToUpper()

month = "JAN"

If you are not getting the result then see if your column in the table is

datetime or smalldate

if it is not then change it to datetime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM