1

I want to know if it is possible to have a custom default value in a model,

example I have a model that has a DateUpdated field and UpdateBy field

in my model

public class Document
{
    public int Id { get; set; }

    [Required, StringLength(2)]
    public string DocumentCode { get; set; }

    public string DocumentName { get; set; }

    public DateTime DateUpdated { get; set; } = DateTime.Now;

    //Id of the current logged user
    public string UpdatedBy { get; set; }
}

In my model i have this line of code public DateTime DateUpdated { get; set; } = DateTime.Now; to set the default value for DateUpdated

Now I also want that in my UpdateBy field, UpdatedBy is current id of login user.

I want to do it something like this

//Id of the current logged user
    public string UpdatedBy { get; set; } = GetCurrentUserId();

But I'm not sure and stuck, I don't if it is possible or a good way to do it.

So far, Here is my code to provide the UpdateBy

if (ModelState.IsValid)
        {
            document.UpdatedBy = (await _userManager.GetUserAsync(HttpContext.User)).Id.ToString();
            _context.Add(document);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(document);

I always rewrite the code in every Create/Edit and I have many controllers that has the same scenario. I feel like it is redundant, I just want to know what is the best clean way to do it. Thank you..

  • Might be worth looking at this: https://stackoverflow.com/questions/7641552/overriding-savechanges-and-setting-modifieddate-but-how-do-i-set-modifiedby – SpruceMoose Feb 13 '18 at 00:40
  • 2
    A default constructor might be a good place to set default values – Rufus L Feb 13 '18 at 01:30

0 Answers0