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