Dakait
Dakait

Reputation: 2620

Generate GUID for Primary key automatically In EF5

I'm using Guids as primary key for the entities in my database, using the model binding feature of asp.net 4.5 web forms when im inserting a record in the database using entity framework 5 im doing something like

public void onInsert([Control("ControlID")] int? countryID){

 if(countryID.hasValue){
    var DbEntityToInsert = new DbEntity(); //where DbEntity is the class generated by the EF
    TryUpdateModel(DbEntityToInsert);
    DbEntityToInsert.GuidPK = Guid.NewGuid();
    if(Page.ModelState.IsValid){
     using(var db = new DatabaseContext()){
      db.Add(DbEntityToInsert);
      db.Save();
     }//using ends
    }//modelstate.isvalid if ends
  }//countryid.hasvalue ends
 }//main method ends

now i wanted to ask is there a way i can tell EF to generate a Guid for the PK while inserting a new record so i dont have to write the line

  DbEntityToInsert.GuidPK = Guid.NewGuid();

Upvotes: 0

Views: 439

Answers (1)

Slauma
Slauma

Reputation: 177133

You can try to override SaveChanges in your derived context. The main task is to find out if an entity has a GuidPK property as primary key. Here is an attempt using reflection:

public override int SaveChanges()
{
    this.ChangeTracker.DetectChanges();

    var addedEntities = this.ChangeTracker.Entries()
        .Where(e => e.State == EntityState.Added)
        .Select(e => new
        {
            Entity = e.Entity,
            PropertyInfo = e.Entity.GetType().GetProperty("GuidPK")
        })
        .Where(x => x.PropertyInfo != null && x.PropertyInfo.CanWrite);

    foreach (var x in addedEntities)
        x.PropertyInfo.SetValue(x.Entity, Guid.NewGuid());

    return base.SaveChanges();
}

To avoid reflection here you could have a common interface that is implemented by all your entities that use a GuidPK property as PK:

public interface IEntityWithGuidPK
{
    Guid GuidPK { get; set; }
}

public class DbEntity : IEntityWithGuidPK
{
    public Guid GuidPK { get; set; }
    // ...
}

Then the code in SaveChanges could be:

    //...

    var addedEntities = this.ChangeTracker.Entries()
        .Where(e => e.State == EntityState.Added &&
            e.Entity is IEntityWithGuidPK)
        .Select(e => e.Entity as IEntityWithGuidPK);

    foreach (var e in addedEntities)
        e.GuidPK = Guid.NewGuid();

    //...

Upvotes: 1

Related Questions