Web API using Entity Framework to query by multiple columns

asp.net-mvc-5.2 asp.net-web-api entity-framework-6

Question

Using EF6, I'm creating a Web API project. When I add a Controller, the EntityKey is the default column queried ("Id"), which works fine. I want to add additional columns to query within the same table via the API, which I'm unable to get to work.

For example, I can query Id (/api/CtrlName/123456), but if I want to query via say a Title column, /api/CtrlName?title="value", it always comes back with a NotFound message.

Is there a simple tutorial to set this functionality up within the Controller?

    [ResponseType(typeof(Article))]
    public IHttpActionResult GetArticle(string id)
    {
        Article article = db.Articles.Find(id);
        if (article == null)
        {
            return NotFound();
        }

        return Ok(article);
    }

    [ResponseType(typeof (Article))]
    public IHttpActionResult GetArticleByTitle(string title)
    {
        Article article = db.Articles.Find(title);
        {
            if (article == null)
                return NotFound();
        }

        return Ok(article);
    }

    private bool ArticleExists(string id)
    {
        return db.Articles.Count(e => e.Id == id) > 0;
    }

    private bool ArticleExistsTitle(string title)
    {
        return db.Articles.Count(b => b.title.Contains(title) ) > 0;
    }
1
0
3/16/2015 9:52:26 PM

Popular Answer

The issue is that .Find() only works on the Primary Key. In order to work on other columns, you must use .Where (e.g. db.Articles.Where(i => i.Title.Equals(title)).

0
3/17/2015 2:11:14 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow