Question

let's say I have this code :

var foo = new Foo { Id = Guid.NewGuid(); }

var id = foo.Id; // have access to the id here

context.Add(foo);
context.SaveChanges();

How does Guid.NewGuid() avoid collision with a Guid already on my Database? What if the generated guid already exists on the database ? I don't get it.

Using a autoincrement id is obvious, but I won't know the id until I save to the database which make sense. How does guid does it to work 'different' ?

Was it helpful?

Solution

How does Guid.NewGuid() avoid collision with a Guid already on my Database?

If doesn't. You just have different ids generated each time. Actually chance of generating equal Guids is very low.

What if the generated guid already exists on the database?

If you will provide same Guid value, you will have violation of primary key constraint. Following code will produce Cannot insert duplicate key error

var guid = Guid.NewGuid();
context.Foos.Add(new Foo { Id = guid });
context.Foos.Add(new Foo { Id = guid });
context.SaveChanges();

NOTE: You can ask Entity Framework to generate guid key on database side for you. Use DatabaseGenerated attribute for that:

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public int Value { get; set; }
}    

Now just save Foo without generating key manually, and EF will update id with guid generated by database:

var foo = new Foo { Value = 42 };
context.Foos.Add(foo); // id is 00000000-0000-0000-0000-000000000000
context.SaveChanges();     
// now id has value generated during insert 421ffa94-1970-e311-9e31-001fd09468de

OTHER TIPS

According to MSDN, there is a very low probability that it could be duplicated.

Remarks Section:

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

If Id is a Unique/Primary Key of your Foo table, it will throw an error in case if it is duplicated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top