Search code examples
c#oracle-databaseentity-framework-corescaffolding

How to fix "Only one column per table can be configured as 'Identity'. Call 'ValueGeneratedNever' ... in Ef Core and Oracle


I have an Oracle Database. I tried to Scaffold my data model into my .net core 5 project using EF Core which has been done successfully, but when I try to Get a list from I get this Error:

Only one column per table can be configured as 'Identity'. Call 'ValueGeneratedNever' for properties that should not use 'Identity'.

The table in database has just one identity column which "ID" and the other column is a simple Number without precision. here is my model after reverse engineering:

modelBuilder.Entity<CreBranches>(entity =>
        {
            entity.ToTable("CRE_BRANCHES");

            entity.Property(e => e.Id).HasColumnName("ID");

            entity.Property(e => e.BranchCode)
                .HasColumnName("BRANCH_CODE")
                .HasColumnType("NUMBER")
                .ValueGeneratedOnAdd();

            entity.Property(e => e.CreationDate)
                .HasColumnName("CREATION_DATE")
                .HasColumnType("TIMESTAMP(6)")
                .ValueGeneratedOnAdd();}

When I just make a simple select from each model, I get this error:

The properties 'CreBranches.BranchCode', 'CreBranches.Id' are configured to use 'Identity' value generator and are mapped to the same table 'Cre_branches'. Only one column per table can be configured as 'Identity'. Call 'ValueGeneratedNever' for properties that should not use 'Identity'.

CRE_BRANCHES:

enter image description here

when I remove ValueGeneratedOnAdd(), it works. Does anybody know what to do?


Solution

  • I finally solved the problem.

    The problem was I did not set default value for my numeric columns in Oracle. I set the default value of these columns to NULL and the problem been solved using the following command:

    ALTER TABLE table_name MODIFY column_name DEFAULT NULL;
    

    So, after scaffolding the database, EF added .HasDefaultValueSql("NULL") to the fluent API:

    entity.Property(e => e.ColumnName)
                    .ValueGeneratedOnAdd()
                    .HasColumnName("Column_Name")
                    .HasDefaultValueSql("NULL");
    

    Thank you all.