【问题标题】:Update a data without modifying CreatedBy and CreatedDate while updating the existing record [duplicate]在更新现有记录时更新数据而不修改 CreatedBy 和 CreatedDate [重复]
【发布时间】:2019-06-15 17:21:46
【问题描述】:

在更新数据库中已经存在的数据时,该表具有 CreatedBy、CreatedDate、ModifiedBy、ModifiedDate 等列。 CreatedBy 和 CreatedDate 在创建新行时插入,但在更新时,我不需要更新 CreatedBy 和 CreatedDate,我只需要修改 ModifiedBy 和 ModifiedDate。

如以下代码所示,它会将 CreatedBy 更新为 null 并将 CreatedDate 更新为 01/01/0001 之类的东西。

_Context.UserProfile.Update(userProfile);

我的模型是这样的,

public class MyModelUserProfile
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    public string FirstName { get; set; }
    public string CreatedBy { get; set; }
    public string ModifiedBy { get; set; }
}

有什么方法可以避免更新 CreatedBy 和 CreatedDate 列?我可以通过其电子邮件 ID 获取该特定记录来做到这一点,但我不想为此再次访问数据库。

【问题讨论】:

  • 如下代码所示——这并没有说明为什么这些属性/字段应该被更新。取决于如何修改userProfile。顺便说一句,日期属性在哪里?
  • 使用链接中的答案,但指定Ignore而不是Throw

标签: c# .net-core entity-framework-core dbcontext


【解决方案1】:

您不需要更改模型中的 CreatedByCreatedDate 属性。

你的场景在这里:

  1. 从数据库中读取您的实体
  2. 修改您计划更新的属性
  3. 不要修改CreatedByCreatedDate
  4. 将模型更新到数据库

另外你的模型设计的不好。 您需要使用DateTime 表示日期,使用Int32 表示数字。

请像这样更改您的模型:

public class MyModelUserProfile
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    public string FirstName { get; set; }
    public int CreatedBy { get; set; }
    public int ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public DateTime CreatedDate { get; set; }
}

【讨论】:

  • 完美!我的头脑有时会像哑巴一样工作。还有一个问题,我不能通过只访问数据库一次来做到这一点吗?
  • @ChandanYS 请参阅here 了解一些替代方案。
猜你喜欢
  • 2018-09-23
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多