Auto-generated Guid in Entity Framework Code First

When you create an entity in Code First model, you might need a Guid field. In addition you might want SQL Server should auto-generate values for that field. This can be done with an annotation as following:

After migration you will find that ClientGuid field has a default value newsequentialid().

Auto-generated Guid in Code First

The most curious thing is the default value in SQL Server database could be created only at the creation of field itself. If you create a field without an identity option first, then you try to add annotation, SQL Server does not add a default value.

In that case you can recreate database (but it’s not appropriate in many cases) or to add a class constructor to explicitly assign new Guid value as following:

2 Replies to “Auto-generated Guid in Entity Framework Code First”

Leave a Reply

Your email address will not be published. Required fields are marked *