C# 更新现有记录时不修改CreatedBy和CreatedDate而更新数据

C# 更新现有记录时不修改CreatedBy和CreatedDate而更新数据,c#,.net-core,entity-framework-core,dbcontext,C#,.net Core,Entity Framework Core,Dbcontext,因为我正在更新数据库中已经存在的数据,并且该表包含CreatedBy、CreatedDate、ModifiedBy、ModifiedDate等列。创建新行时会插入CreatedBy和CreatedDate,但在更新时,我不需要更新CreatedBy和CreatedDate,只需要修改ModifiedBy和ModifiedDate 如下面的代码所示,它会将CreatedBy更新为null,将CreatedDate更新为01/01/0001,类似这样的内容 _Context.UserProfile.

因为我正在更新数据库中已经存在的数据,并且该表包含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获取特定记录,但我不想为此再次访问数据库。

您不需要更改模型中的
CreatedBy
CreatedDate
属性

您的场景如下:

  • 从数据库中读取实体
  • 修改要更新的属性
  • 不要修改
    CreatedBy
    CreatedDate
  • 将模型更新到数据库
  • 而且你的模型设计得不好。 日期需要使用
    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; }
    }
    

    您不需要更改模型中的
    CreatedBy
    CreatedDate
    属性

    您的场景如下:

  • 从数据库中读取实体
  • 修改要更新的属性
  • 不要修改
    CreatedBy
    CreatedDate
  • 将模型更新到数据库
  • 而且你的模型设计得不好。 日期需要使用
    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; }
    }
    

    如下面的代码所示——这并没有说明为什么要更新这些属性/字段。取决于
    userProfile
    的修改方式。顺便说一句,日期属性在哪里?使用链接中的答案,但指定
    忽略
    ,而不是
    抛出
    。如下面的代码所示——这并没有说明为什么要更新这些属性/字段。取决于
    userProfile
    的修改方式。顺便说一句,日期属性在哪里?使用链接中的答案,但指定
    Ignore
    而不是
    Throw
    。完美!我的头脑有时会像哑巴一样工作。还有一个问题,我不能只点击数据库一次吗?@ChandanYS看看其他的选择。太好了!我的头脑有时会像哑巴一样工作。还有一个问题,我不能只点击数据库一次吗?@ChandanYS看看其他的选择。