LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method when attempting to parse a column for inequality comparisons

后端 未结 7 1098
抹茶落季
抹茶落季 2020-12-09 15:55

I have following code in my page:

var myVar= Entity.SetName
                 .Where(p => int.Parse(p.ID) >= start &&
                  int.Pars         


        
相关标签:
7条回答
  • 2020-12-09 16:15

    You cannot convert in query at the end of the query you can parse it with select.

    If you want to keep an integer list, you can use it.

    var locquery = entityDataContainer.application
                    .Where(x => x.AttributeType == "LOC").AsQueryable()                                                        
                    .Select(x => x.AttributeValue).ToList();
    
    var locCount = locquery.Select(int.Parse).ToList().Sum();
    
    0 讨论(0)
  • 2020-12-09 16:20

    To Convert string to int, you have to make it Enumerable, then you can make sort or anything you like

      var list = db.UserEntriesTable.AsEnumerable().Select(x => new {
    
                 Name = x.Name,
    
                 Roll = Convert.ToInt32(x.Roll),
    
                 Mobile = x.Mobile
    
            }).OrderBy(x => x.Roll).ToList();
    
    0 讨论(0)
  • 2020-12-09 16:20

    Although it's not efficient, you should be able to load all rows, and then use LINQ to Objects:

    var myVar= Entity.SetName.ToList()
                     .Where(p => int.Parse(p.ID) >= start &&
                      int.Parse(p.ID) <= end);
    
    0 讨论(0)
  • 2020-12-09 16:24

    First, I would highly recommend to check your database design, whether there is a really good reason for ID to be a string. I would consider changing the ID DB type to int and you will get rid of this problem with converting.

    The error you get means, that EF does not know how to convert the method Int32.Parse() to SQL. Basically you have two options how to deal with that:

    Do the comparison outside the linq to entities:

    var myVar= Entity.SetName.AsEnumerable()
                     .Where(p => int.Parse(p.ID) >= start &&
                      int.Parse(p.ID) <= end);
    

    But this is not recommended, because you are reading whole result set from DB, before applying the where condition.

    Or make custom model defined function as described in this post on SO:

    Convert String to Int in EF 4.0 or Entity Framework: Where do I extend the CSDL/MSL?

    0 讨论(0)
  • 2020-12-09 16:32

    First try to convert to int then pass that variable name

    int catgry = Convert.ToInt32(customercategory.OWNERSHIP_TYPE);
    var customerCateg = (from d in _db.tbl_SIL_CUSTOMER_CATEGORY_MST
        .Where(d => d.CAT_ID == catgry) select d.CAT_TYPE).SingleOrDefault();
    
    0 讨论(0)
  • 2020-12-09 16:36

    move the parse function out of linq expression.

    int id = int.Parse(p.ID);
    var myVar= Entity.SetName
    .Where(p => id >= start && id <= end);
    
    0 讨论(0)
提交回复
热议问题