简体   繁体   English

将字符串变量作为查询参数传递给LINQ查询

[英]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. 我试图通过我的MVC控制器中的POST请求将字符串变量传递到LINQ查询中。 I have tried a number of variations on the dynamic LINQ examples(which seems to be the primary recommended method. 我已经在动态LINQ示例中尝试了多种变体(这似乎是推荐的主要方法。

EXPECTED RESULT 预期结果

An IEnumerable array which contains results based on specified SiteID displayed in an ng-repeat. IEnumerable数组,其中包含基于ng-repeat中显示的指定SiteID的结果。

NON-DYNAMIC-LINQ QUERY 非动态LINQ查询

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 动态LINQ查询

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. 如果两个linq查询都未能返回结果,则我怀疑您传递的值不是您期望的值。 Try hardcoding a value for siteID to a known good value and see if that works. 尝试将siteID的值硬编码为已知的适当值,然后查看是否可行。 (I prefer the first query, but both are fine) (我更喜欢第一个查询,但是都很好)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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