Entity Framework Code First Using Guid as Identity with another Identity Column

放肆的年华 提交于 2019-11-27 06:25:18

This ended up working for me, Entity Framework 5.

  1. Turn off automatic migrations
  2. Migrate to create the initial table, no frills
  3. Declare the ClusterId as Identity (annotation)

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override int ClusterId { get; set; }
    
  4. Migrate

  5. Declare the pk property Id as Identity after the other one has been updated

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override Guid Id { get; set; }
    
    • bonus: EF seems to assume Id is primary key, so you don't need [Key, Required]
  6. Create the migration code like add-migration TrickEfIntoAutogeneratingMultipleColumns

  7. In the Up() method, in the AlterColumn statement, tell the database to autogenerate the GUID by declaring the defaultSqlValue
    • AlterColumn(theTable, "Id", c => c.Guid(nullable: false, identity: true, defaultValueSql: "newid()"));
  8. Migrate

This seems to "trick" EF, in the sense that it assumes both columns are identities and reacts accordingly. During migration, it tries to make another column an identity, but seemingly doesn't care when that silently fails -- you end up with one marked as Identity and the other with a default value.

During normal code operation, when EF goes through the SaveChanges/ChangeTracking steps, because it sees the Id property as an Identity it does it's whole "assign temporary key" thing, so that it's not trying to use the default 0000000... value, and instead lets the database generate it using the default value function you specified.

(I would have thought annotating this field as Computed would have accomplished the same thing, but...the errors I mentioned in the question...boo...)

And, because the ClusterId field is also an Identity in code, and really is an Identity in the database, it autoincrements as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!