Autogenerate GUID, which is not a primary key in the Entity Framework

I am transitioning to the Entity Framework from an existing model and database. There are several tables in this database with GUID columns that are not primary keys (or keys at all!). Each table has an identifier column. The GUID columns set the ROWGUIDCOL property, as well as DEFAULT (newid ()).

Now, when I insert into the database, I get all the zeros for this column.

I tried using data annotations:

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

The problem is that it removes the identity property in my ID column (and gives me insertion errors). In addition, I noticed that for the next migration, EF actually generates identical SQL for both the up and down methods:

 public override void Up() { AlterColumn("dbo.Client", "Guid", c => c.Guid(nullable: false, identity: true)); } public override void Down() { AlterColumn("dbo.Client", "Guid", c => c.Guid(nullable: false)); } 

Generated sql:

 ALTER TABLE [dbo].[Client] ALTER COLUMN [Guid] [uniqueidentifier] NOT NULL 

Why does the above migration create the same sql for both statements? How to get EF to generate GUID? Can I / should I do this in the client (code) space? If I must, how can I guarantee uniqueness between tables?

+5
source share
2 answers

DatabaseGenerationOption.Identity should be used for the identity column.

Try using DatabaseGenerationOption.Computed instead. It should prevent EF from sending the value when the column is inserted, and it should correctly output the value generated by db to SaveChanges.

+2
source

I got some errors when trying to convert pre-existing ID columns into GUIDs. The calculation will not work, as the identification will not work. Setting to DatabaseGeneratedOption.None will result in errors indicating that I could not insert zero into the required field. In my constructor, I had a NewGuid generation, but that didn't help either.

To make it work, I deleted my .cs and Migration files. Then, using dataannotations, I was able to defeat the system by setting a new GUID in Key, DatabaseGeneratedOption.None, and then placing the support field with the ID property. This made my getter look at the private field, determine if it was Guid.Empty, and if so, to create a new GUID for me.

  private Guid id = Guid.Empty; [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] [HiddenInput(DisplayValue = false)] public Guid CompanyId { get { if(id==Guid.Empty) id = new Guid(); return id; } set { id = value; } } 
+1
source

Source: https://habr.com/ru/post/1204676/


All Articles