I am creating asp.net mvc4 sample.In this i created Id column as GUID in Sample table of datacontext.
public class Sample
{
[Required]
public Guid ID { get; set; }
[Required]
public string FirstName { get; set; }
}
This is entity table
CreateTable(
"dbo.Samples",
c => new
{
ID = c.Guid(nullable: false),
FirstName = c.String(nullable: false)
})
.PrimaryKey(t => t.ID);
Id pass 00000000-0000-0000-0000-000000000000.
How to set newid()
to GUID
and where i have to set.
The answer of Paul is right but the implementation of the Sequential Guid can be improved. This implementation of sequential guid increments more often and prevents same numbers if created on the same server.
To prevent link rot, the code:
When using Entity Framework Core 2.1.1 I use:
Then in the migration, add in the defaultValueSql parameter as below:
This ensures that the sql server is responsible for generating a sequential guid which is going to be better than rolling your own.
If you do not want the downsides of using sequential guids you can use "newid()" instead.
I would recommend just using
long
for your ID type. It "just works" with and has some performance gains over GUID. But if you want to use a GUID, you should use a Sequential GUID and set it in the constructor. I would also make ID aprivate
setter:Sequential GUID
I know that question is quite old, but if someone has such problem I suggest such solution:
You can get newid from SQL database when your new object is creating. For me it works. :) (but I don't know it is good practice)
How use it:
I encountered the same problem with Nlog logging to database . What I did is to purposely open the migration file and did the following changes
the identity parameter actually created the table with
defaultvalue
asnewsequentialid()
in the table .This can also be done with attributes: