自动为主键生成GUID在EF5中

时间:2013-05-25 15:01:25

标签: asp.net entity-framework-5

我正在使用Guids作为我数据库中实体的主键,当我使用实体框架5在数据库中插入记录时,使用asp.net 4.5 Web表单的模型绑定功能实现类似

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

现在我想问一下,有什么方法可以告诉EF在插入新记录时为PK生成Guid,所以我不必写行

  DbEntityToInsert.GuidPK = Guid.NewGuid();

1 个答案:

答案 0 :(得分:1)

您可以尝试在派生的上下文中覆盖SaveChanges。主要任务是查明实体是否具有GuidPK属性作为主键。以下是使用反射的尝试:

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();
}

为避免在此反思,您可以拥有一个公共接口,该接口由使用GuidPK属性作为PK的所有实体实现:

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

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

然后SaveChanges中的代码可以是:

    //...

    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();

    //...