简体   繁体   中英

EF Core 3 Error when trying to save object with enumeration class properties

I got a couple of entities that derive from a enumeration class (as described in this link: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types ) Things like Genders, Countries. Don't want to change this since it works really well.

Trying to implement EF Core 3 (I'm new to it, coming from dapper.net)

So I'd say have a Gender class:

public class Gender : Enumeration
    {
        public static Gender Female = new Gender(1, "Female");
        public static Gender Male = new Gender(2, "Male");
        public static Gender Unknown = new Gender(999, "Unknown");

        public Gender(int id, string name)
            : base(id, name)
        {
        }
    }

So in my DataContext I for instance have public DbSet<Gender> Genders { get; set; } public DbSet<Gender> Genders { get; set; }

And seed the data in OnModelCreating:

private void SeedGenders(ModelBuilder modelBuilder)
        {
            var values = Enumeration.GetAll<Gender>().ToList();
            modelBuilder.Entity<Gender>()
                .HasData(values);
        }

However later I'd say have newPerson.Gender = Gender.Female; but then I try to save it with:

await  _repository.Insert(newPerson);

I will get an error

Cannot insert explicit value for identity column in table 'Genders' when IDENTITY_INSERT is set to OFF.

Probably something simple but I cannot understand since I'm not trying to add anything to Genders, I'm trying to save an instance of a person.

My repository worked just fine until I started try add these enumeration classes with the following code

public async Task<Person> Insert(Person person)
{
    await _context.Persons.AddAsync(person);
    await _context.SaveChangesAsync();
    return person;
}

When you set

newPerson.Gender =   Gender.Female;

That value ( Gender.Female ) is new to entity-framework. It doesn't magically know it already exists in the database. And it doesn't attempt to look for it either. Entity Framework will attempt to save it to the database, and since it already has an Id value (not Zero) it tries to insert the gender and fails with that specific error.

You can fix your problem by telling entity framework not to save the Gender.

newPerson.Gender = Gender.Female
dbContext.Entry(Gender.Female).State = EntityState.Detached;
await  _repository.Insert(newPerson);

Tell EF that this entity is detached simply means, don't save it to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM