I`m facing the following problem when dealing with inserting new entities in the DB that has Guid as primary keys - EF 5 with Code first approach.
I know there are a lot similar topics as I was roving for hours for this issue, but I couldn`t find topic with this problem.
As an example, my POCO class is:
public class EntityRole : IAdminModel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[Display(Name = "Role code")]
[MaxLength(20)]
public string RoleCode { get; set; }
[Display(Name = "Entities Assigned")]
[InverseProperty("Role")]
public List<Entity> Entities { get; set; }
}
RoleCode and Name are just text data, that is editable in the admin panel, so don`t consider those field names.
When adding new entity I don`t specify primary key values. So far so good, all works fine here. As a primary key field that requires value and has auto-generation of values, it is supposed not to always specify Id, but if I set a value, it should be kept (if identity insert is enabled).
But in some cases I want to specify a primary key value, for example for initial seeding of my DB with values. I need it for later processing - lets just say I need that specific Guid to be there. So if I have in my Configuration class:
// Initial data seed
protected override void Seed(WebPortalDbContext context)
{
context.MenuItems.AddOrUpdate(
m => m.Id,
new EntityRole {Id = new Guid("268bf332-910e-4ea1-92f8-1ac0611f4c62"), Name = "Some name", RoleCode = "SN"},
);
}
The Guid key setting goes not work even if I do a regular add:
using (var context = new MyDBContext())
{
context.MenuItems.Add(
new Entity() {Id = new Guid("<some gu