efcore icon indicating copy to clipboard operation
efcore copied to clipboard

UpdatedDate not actualize by value generate during unit tests with SQLite in memory

Open kcomin opened this issue 7 years ago • 15 comments

Hello,

I try to actualize my UpdatedDate field in my UserEntity object by value generate during my unit tests.

Here my UserEntity :

public class UserEntity
    {
        /// <summary>
        /// Id.
        /// </summary>
        [Key]
        [Column("USER_UID")]
        public int Id { get; set; }

        /// <summary>
        /// User Lastname.
        /// </summary>
        [Required]
        [Column("USER_LASTNAME")]
        public string LastName { get; set; }

        /// <summary>
        /// User Firstname.
        /// </summary>
        [Required]
        [Column("USER_FIRSTNAME")]
        public string FirstName { get; set; }

        /// <summary>
        /// Created date.
        /// </summary>
        [Column("CREATED_DATE")]
        [DataType(DataType.DateTime)]
        [Required]
        public DateTime CreatedDate { get; set; }

        /// <summary>
        /// Updated date.
        /// </summary>
        [Column("UPDATED_DATE")]
        [DataType(DataType.DateTime)]
        public DateTime UpdatedDate { get; set; }
    }

I added anotations[DatabaseGenerated(DatabaseGeneratedOption.Identity)]for CreatedDate and[DatabaseGenerated(DatabaseGeneratedOption.Computed)]for UpdatedDate. I generate migrations and anotations MySql:ValueGenerationStrategy are added for MySql.

In my migrations :

migrationBuilder.CreateTable(
                name: "DATA_USER",
                columns: table => new
                {
                    USER_UID = table.Column<int>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    CREATED_DATE = table.Column<DateTime>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    UPDATED_DATE = table.Column<DateTime>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn),
                    USER_LASTNAME = table.Column<string>(nullable: false),
                    USER_FIRSTNAME = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_DATA_USER", x => x.USER_UID);
                });

It works in production but not for unit tests that use SQLite in-memory !

I try to add ValueGeneratedOnAdd() and ValueGeneratedOnAddOrUpdate() just for unit tests :

builder.Entity<UserEntity>().Property(c => c.CreatedDate).ValueGeneratedOnAdd().HasDefaultValueSql("CURRENT_TIMESTAMP");
builder.Entity<UserEntity>().Property(c => c.UpdatedDate).ValueGeneratedOnAddOrUpdate().HasDefaultValueSql("CURRENT_TIMESTAMP");

It's ok for CreatedDate and UpdatedDate while adding a user but during editing, UpdatedDate is not actualized.

EF Core version: 2.2 Database Provider: Pomelo.EntityFrameworkCore.MySql Version="2.2.0" Operating system: Ubuntu 18.04 IDE: 1.37.1

Thanks for your help, Kévin

kcomin avatar Aug 30 '19 13:08 kcomin

@kcomin To clarify, is your question how to use computed columns with a SQLite in-memory database?

ajcvickers avatar Aug 30 '19 20:08 ajcvickers

@ajcvickers, yes that's right, I work with @kcomin and that's what we want.

Because computed columns annocation "DatabaseGenerated(DatabaseGeneratedOption.Computed)]" work well on the application with Mysql provider but our tests uses SQLite In-momry and it does not work with..

We can not find a solution that works for both uses at the same time.

aborderon avatar Aug 31 '19 13:08 aborderon

@ajcvickers Do you have any information to give us ? Thanks for your help

aborderon avatar Sep 05 '19 10:09 aborderon

@bricelam to follow up.

ajcvickers avatar Sep 06 '19 17:09 ajcvickers

You'll either need to use a trigger on SQLite to generate a value for UpdatedDate, or you can just override DbContext.SaveChanges() and set the value there.

CREATE TRIGGER SET_DATA_USER_UPDATED_DATE
AFTER UPDATE ON DATA_USER
BEGIN
    UPDATE DATA_USER
    SET UPDATED_DATE = CURRENT_TIMESTAMP
    WHERE ROWID = NEW.ROWID;
END

bricelam avatar Sep 06 '19 20:09 bricelam

Pair the trigger with ValueGeneratedOnAddOrUpdate and HasDefaultValueSql to get the behavior you want.

bricelam avatar Sep 06 '19 20:09 bricelam

Thanks @bricelam for your feedback. I understand your solution.

Do I need to define a migration for the trigger and specify the use that can only be used by the SQLite provider?

How to apply the trigger for all tables automatically? ..

aborderon avatar Sep 08 '19 17:09 aborderon

If you’re using Migrations, you can do it that way. If not, do it during database initialization (e.g. after EnsureCreated returns true).

For each table, you can generate SQL in a foreach loop...

if (db.Database.EnsureCreated())
{
    foreach (var table in dB.Model.EntityTypes().Select(t => t. TableName).Distinct())
    {
        dB.Database.ExecuteSqlComnand(“create trigger...” + table);
    }
}

Sorry, no magical answers here. 🙃

bricelam avatar Sep 09 '19 02:09 bricelam

Okay I see.

Do you have a solution to iterate on all entities to use FromSql ? Because ExecuteSqlCommand does not support interpolation with SQLite ...

ExecuteSqlCommand works well without interpolation but I do not want to define a trigger for each of my entities.

aborderon avatar Sep 09 '19 09:09 aborderon

I’m not sure I understand. Are you trying to trying to use a SQL parameter to define the trigger? You can’t do that

bricelam avatar Sep 09 '19 14:09 bricelam

Yes I tried with interpolation and SQLiteParamater but I always get an exception of this type: SQLite error (1): near “{0}”: syntax error

If I do not use a parameter and enter the name of the tables and trigger manually I have no exception.

aborderon avatar Sep 09 '19 14:09 aborderon

@bricelam - Can you conclude this?

smitpatel avatar Sep 20 '19 17:09 smitpatel

@aborderon correct. SQLite syntax does not allow a parameter reference token there. You need to send a separate statement for each trigger.

bricelam avatar Sep 20 '19 19:09 bricelam

That is what I thought. Thank you for your help.

aborderon avatar Sep 21 '19 08:09 aborderon

Isn't it possible to change the Sqlite adapter to populate the DateTime properties, if ValueGeneratedOnAddOrUpdate() is defined? Or is there something inherent to Sqlite that explains the different behaviour? In Mysql/MariaDb (pomelo adapter) it works as expected.

timmi-on-rails avatar Jun 26 '20 20:06 timmi-on-rails