0

I am creating an invoice table with code first migrations, the table needs to have a unique invoice number. I do not want to make this field my primary key. My preferred method to go about this is to use Guid for the invoice number, this way a unique value gets created everytime I insert an invoice item. I could generate random strings but I do not want to have to write logic to create random strings.

Please note, I do not want to install any external libraries for this. I am doing my mappings with Fluent API and not Data Annotations. Please factor that into your answer.

Is this possible for me to achieve just using a Guid column?

Thanks in advance.

strizzwald
  • 643
  • 1
  • 8
  • 19

2 Answers2

0

When defining your table in SQL Server, define the column as uniqueidentifier NOT NULL DEFAULT newid()

Timothy Stepanski
  • 1,186
  • 7
  • 21
  • Thank you for your answer. I am using Code First Migrations so I am not actually defining the table in SQL Server. I have to make it so that NOT NULL DEFAULT is inferred from my Fluent API mapping – strizzwald Jun 09 '16 at 13:18
  • I believe you would have to manually alter the table in the Migration's Up and Down functions. See this for more information https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/ It's about date columns, but should apply equally to guids. – Bradley Uffner Jun 09 '16 at 13:32
  • Bradley is correct. Using code first doesn't preclude you from altering the table definitions after initial creation. Furthermore, you should source control your database project anyway. – Timothy Stepanski Jun 09 '16 at 13:40
  • Thank you, I will try this. – strizzwald Jun 10 '16 at 10:31
  • This does not work. EF6 will insert 00000000000000000 Guid into the database and NEWID() is never called. This will fill the table with 0000000-Guids – Diana Jan 17 '21 at 15:34
0

In your Invoice class entity, create a column as below;

public Guid InvoiceNumber {get;set;}

with a constructor of

public Invoice(){
      InvoiceNumber = Guid.NewGuid();
}

upon newing up a Invoice you should have a Guid pre-populated

uk2k05
  • 368
  • 2
  • 9
  • Thank you, will this handle duplicate primary keys as well. In other words, if I do this is there a chance that the same Guid will be generated twice? – strizzwald Jun 10 '16 at 16:12
  • The chances of the same GUID appearing twice is very, very unlikely.. http://stackoverflow.com/questions/39771/is-a-guid-unique-100-of-the-time – uk2k05 Jun 14 '16 at 08:16