0

I'm working on ASP.NET and I have 2 ways to get an item in database:

  1. The first:
public Post Get(string postId)
    => !string.IsNullOrEmpty(postId) 
       ? _dbContext.Posts.SingleOrDefault(x => x.Id == postId) : null;

Usage:

var post = Get("someid");

if (post != null)
{
    // do stuff...
}
  1. The second:
public bool TryGetPost(string postId, out Post post)
{
    if (!string.IsNullOrEmpty(postId))
    {
        post = _dbContext.Posts.SingleOrDefault(x => x.Id == postId);

        return post != null;
    }

    post = null;
    return false;
}

Usage:

if (TryGetPost("someid", out Post post))
{
    // do stuff...
}

Could you please teach me when to use the first/second?

Is there another way which is better than them?

  • 1
    Might be a better fit for code review (but review their help first). Doesn't seem a good fit for SO. – Damien_The_Unbeliever Nov 29 '18 at 07:09
  • Have a look at https://stackoverflow.com/questions/17207712/when-is-try-supposed-to-be-used-in-c-sharp-method-names - contains some helpful links for background information. – Ralf Bönning Nov 29 '18 at 07:17
  • Beyond official Microsoft's guidance in linked [duplicate](https://stackoverflow.com/questions/17207712/when-is-try-supposed-to-be-used-in-c-sharp-method-names) there is not much SO could provide you with and stay objective. As @Damien_The_Unbeliever said this is code style question and does not fit SO as such. – Alexei Levenkov Nov 29 '18 at 07:30

1 Answers1

0

As KISS principle says it should be simple. Assuming that you have to return View from controller the example should look like that:

[HttpGet]
public ActionResult GetItem(int postId)
{
  var post = _dbContext.Posts.FirstOrDefault(x => x.Id == postId);

  if (post != null)
  {
    return View(post);
  }

  return View();
}

This also have many mods and good practices but this will be enough to get data from database and display it to View.

When you save data do database you should use POST method, if you only get something use GET. You can also use PUT method for modifying existing data in database.