Converting a EF CodeFirst Base class to a Inherited class (using table-per-type)

前端 未结 2 989
别那么骄傲
别那么骄傲 2021-01-03 04:42

I am using EF Code First and have two classes defined as follows:

public class User
{
    public int Id { get; set; }
    public string Username { get; set;          


        
相关标签:
2条回答
  • 2021-01-03 05:01

    You were almost there... The key is to detach the existing entity, then attach the new one.

    Here's an example:

    using System.Data;
    using System.Data.Entity;
    using System.Diagnostics;
    
    public class Animal
    {
        public long Id { get; set; }
    }
    
    public class Dog : Animal
    {
    }
    
    public class AnimalsContext : DbContext
    {
        public DbSet<Animal> Animals { get; set; }
    }
    
    
    public class Tester
    {
        public void Test()
        {
            var context = new AnimalsContext();
    
    
            var genericAnimal = new Animal();
            context.Animals.Add(genericAnimal);
            context.SaveChanges();
    
    
            // Make a new clean entity, but copy the ID (important!)
            var dog = new Dog { Id = genericAnimal.Id, };
    
            // Do the old switch-a-roo -- detach the existing one and attach the new one
            // NOTE: the order is important!  Detach existing FIRST, then attach the new one
            context.Entry(genericAnimal).State = EntityState.Detached;
            context.Entry(dog).State = EntityState.Modified;
            context.SaveChanges();
    
    
            var thisShouldBeADog = context.Animals.Find(genericAnimal.Id);
    
            // thisShouldBeADog is indeed a Dog!
            Debug.Assert(thisShouldBeADog is Dog);
    
            // And, of course, all the IDs match because it's the same entity
            Debug.Assert((genericAnimal.Id == dog.Id) && (dog.Id == thisShouldBeADog.Id));
        }
    }
    
    0 讨论(0)
  • 2021-01-03 05:01

    I would create a new record and delete the old record. I don't think you should effectively change the class of an existing object, nor delete and create records attempting to reuse the database key.

    Database primary keys should be meaningless. If you need to assign a meaningful ID to your records then add a new field for that. Think of your stack overflow ID, I bet that's not the primary key in their database.

    0 讨论(0)
提交回复
热议问题