简体   繁体   中英

Pass string variable as query parameter to LINQ query

I am attempting to pass a string variable via a POST request in my MVC controller into a LINQ query. I have tried a number of variations on the dynamic LINQ examples(which seems to be the primary recommended method.

EXPECTED RESULT

An IEnumerable array which contains results based on specified SiteID displayed in an ng-repeat.

NON-DYNAMIC-LINQ QUERY

public IEnumerable<SpecialsViewModel> GetAllSpecialsBySiteID(string siteID)
{
    var query = (from s in _calcContext.Specials
    where s.SiteID == siteID
    select new SpecialsViewModel
    {
        ID = s.ID,
        SiteID = s.SiteID,
        Title = s.Title,
        Description = s.Description,
        Price = s.Price,
        Position = s.Position,
        EffectiveDate = s.EffectiveDate,
        CreationDate = s.CreationDate,
        Status = s.Status,
        LastUpdated = s.LastUpdated
    }).ToList();

    return query;
}

RESULT

No results returned.

DYNAMIC LINQ QUERY

public IEnumerable<SpecialsViewModel> GetAllSpecialsBySiteID(string siteID)
{ 
    var query = (from s in _calcContext.Specials
    select new SpecialsViewModel
    {
        ID = s.ID,
        SiteID = s.SiteID,
        Title = s.Title,
        Description = s.Description,
        Price = s.Price,
        Position = s.Position,
        EffectiveDate = s.EffectiveDate,
        CreationDate = s.CreationDate,
        Status = s.Status,
        LastUpdated = s.LastUpdated
    });

    query = query.Where("SiteID=@0", siteID);

    return query;
}

RESULT

No results returned.

If both of your linq queries fail to return results, I suspect the value you are passing in is not what you expect. Try hardcoding a value for siteID to a known good value and see if that works. (I prefer the first query, but both are fine)

尝试将siteID为int并传递给where子句,例如: where s.SiteID == (int32?)siteID

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