如何创建包含创建元素的人的信息的列

时间:2018-03-12 06:16:19

标签: c# asp.net asp.net-core-mvc asp.net-core-2.0

你能帮我吗?如何创建包含谁创建元素的信息的列(列CreatedBy)我使用Windows身份验证创建了asp net core 2.0 MVC Web-Application。我实现了有关谁最后修改,sucessfuly的信息,但我不知道CreatedBy。 我的模特是

 public class TestModel
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public string CreatedBy { get; set; }
        [DataType(DataType.Date)]
        public DateTime Created { get;}
        public TestModel()
        {
            Created = DateTime.Now;
        }
        public string ModifiedBy { get; set; }
        public DateTime Modified { get; set; }
    }

我的创建控制器

public async Task<IActionResult> Create([Bind("Id,Description")] TestModel testModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(testModel);
                testModel.CreatedBy = this.User.Identity.Name;
               // testModel.ModifiedBy = this.User.Identity.Name;
                testModel.Modified = DateTime.Now;
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(testModel);
        }

编辑控制器

public async Task<IActionResult> Edit(int id, [Bind("Id,Description")] TestModel KestModel)
        {
            if (id != KestModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {

                  await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TestModelExists(KestModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }


            return View();
        }

1 个答案:

答案 0 :(得分:2)

根据您的评论,我了解您要在更新请求上更新modifyby并在创建请求时分配created,

为此你应该检查已经分配的ID,如果已经分配了id而不是更新请求,那么它是创建请求

尝试以下代码更改

public async Task<IActionResult> Create([Bind("Id,Description")] TestModel testModel)
{
    if (ModelState.IsValid)
    {                   
        if(testModel.Id > 0){
            // the entity is already created and it is modify request
            _context.Entry(testModel).State = EntityState.Modified;

            testModel.ModifiedBy = this.User.Identity.Name;
            testModel.Modified = DateTime.Now;
        }
        else{
            // it is create request
            _context.Entry(testModel).State = EntityState.Added;            

            testModel.CreatedBy = this.User.Identity.Name;
            testModel.Created = DateTime.Now;
        }            

        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(testModel);
}