0

It regards Entity Framework 6 but maybe it isn’t related to the version.

I have some class which has Guid Id but by inheritance.

public partial class TestObject : SomeModel<Guid>
{

        public TestObject()
        {
        }

    .
    .
    .
        public virtual ICollection<TestObject1> TestObject1s { get; set; }

        public virtual ICollection<TestObject2> TestObject1s { get; set; }
}


    public abstract class SomeModel<TKey>
    {
        public TKey Id { get; set; }

    }

Right now I would like to change this model to auto generate Id by database. I’ve changed class TestObject by added

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

to

public partial class TestObject : SomeModel<Guid>
{

        public TestObject()
        {
        }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }


    .
    .
    .
        public virtual ICollection<TestObject1> TestObject1s { get; set; }

        public virtual ICollection<TestObject2> TestObject1s { get; set; }
}

But after executing command add-migration test I got empty implementation

public partial class test : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

It means that nothing is going to change. And of course after executing update-Database it didn’t affect the database.

But if I create a completely new class (whose implementation is the same as TestObject). It works and it affects the database.

public partial class TestObjectNew : SomeModel<Guid>
{

        public TestObjectNew()
        {
        }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

    .
    .
    .
        public virtual ICollection<TestObject1> TestObject1s { get; set; }

        public virtual ICollection<TestObject2> TestObject1s { get; set; }


}

Could someone explain this behavior ?

How can I update my class to get auto generation Id by database ?

mariszo
  • 1,799
  • 2
  • 10
  • 12

1 Answers1

0

Did you remove TKey Id from your base class? (Does the base class even serve a purpose now?)

The property should be marked as a Key as well:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Then you can specify the default value in your migration. See: Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

Steve Py
  • 26,149
  • 3
  • 25
  • 43