Reputation: 62
Hi I have a MySQL database connected to my application using EF Core I have just found a bug I'd like to get fixed. I can see that my CreatedDateTime column is set to update to the current timestamp on UPDATE which I don't want as if the user is updating a comment the CreatedDateTime should remain the same but its updated to the current DateTime therefor loosing its original data.
So far I have tried
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTimeOffset CreatedDateTime { get; set; }
and also tried on my configuration entity
public class CommentEntityTypeConfiguration : IEntityTypeConfiguration<Comment>
{
public void Configure(EntityTypeBuilder<Comment> builder)
{
builder.Property(x => x.CreatedDateTime).ValueGeneratedNever();
}
}
And I have tried setting the CreatedDateTime to itself on my update method but it seems like the current timestamp is being set after automatically.
But this isn't having any effect as its still set to update the date & time on every update call, I could just edit the database manually but I'd like to sort it out within EF Core if I can.
The code for my Comment model
public class Comment
{
[Key]
public int Id { get; set; }
public string CommentText { get; set; }
[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTimeOffset CreatedDateTime { get; set; }
public bool IsDeleted { get; set; }
public DateTimeOffset? DeletedDateTime { get; set; }
public virtual User CreatedBy { get; set; }
public void Delete()
{
if (IsDeleted)
{
return;
}
IsDeleted = true;
DeletedDateTime = DateTimeOffset.Now;
}
public void Restore()
{
IsDeleted = false;
DeletedDateTime = null;
}
public void Update(string commentText, DateTimeOffset createdDateTime)
{
CommentText = commentText;
CreatedDateTime = createdDateTime;
}
public Comment()
{
}
public Comment(string comment, int createdById)
{
CommentText = comment;
CreatedById = createdById;
CreatedDateTime = DateTimeOffset.Now;
IsDeleted = false;
}
}
public class CommentEntityTypeConfiguration : IEntityTypeConfiguration<Comment>
{
public void Configure(EntityTypeBuilder<Comment> builder)
{
builder.Property(x => x.CreatedDateTime).ValueGeneratedNever();
}
}
Thank you any help is much appreciated, as I'd love to get this bug sorted.
Upvotes: 0
Views: 1444
Reputation: 43860
You don't need any special attributes. Just make CreatedDateTime nullable:
public DateTimeOffset? CreatedDateTime
and check your database. Fix the column too if it is needed.
Upvotes: 1