A
A
Aricce2021-11-19 08:48:23
PostgreSQL
Aricce, 2021-11-19 08:48:23

Why doesn't it add to psql when NOT NULL GENERATED BY ALWAYS AS IDENTITY?

The bottom line is, I don’t want to fool around with the Id field through sequences or get the last id + 1 every time, I want the auto-generation of the field.
When it is NOT NULL GENERATED BY ALWAYS AS IDENTITY, then everything works fine through insert in SQL, but through EF6 it gives an error PostgresException: 428C9: you cannot insert data into the "Id" column
Here is the field setup code:

public void DistrictConfigure(EntityTypeBuilder<District> modelBuilder)
        {
            modelBuilder
                .ToTable("Districts", "dict");
            modelBuilder.Property(x => x.Id).UseIdentityAlwaysColumn();
        }

In SQL it looks like this:
"Id" integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 )

This is what I'm trying to add:
using (passportEntities db = new passportEntities())
            {
                db.Districts.RemoveRange(db.Districts);
                db.SaveChanges();
                db.Districts.Add(new Districts { Name="test"});
                db.SaveChanges();
            }

And it throws an error, although I don’t touch the Id field at all.
Here is the code of the model itself:
In the application that creates (code first)

public class District
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Sector> Sectors { get; set; } = new List<Sector>();
    }

And in the application that I am writing to transfer data from another database generated (Database first)
public partial class Districts
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Districts()
        {
            this.Sectors = new HashSet<Sectors>();
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Sectors> Sectors { get; set; }
    }


I understand that you can just use sql since it works with such settings, but I would like to figure out why it doesn’t work through the Entity Framework. I also tried in other tables for the sake of the test, where I set attributes in the model
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
and the result is the same.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question