简体   繁体   中英

Entity Framework Generic Insert Method Assign Guid to Primary Key

Is there a way to generically identity the primary key (always a single column) and assign a Guid in a generic Insert method:

For example I have who dbSet classes. Both have a single-field primary key of type Guid:

public class Person
{
   [Key]
   [Required]
   public Guid personId {get; set;}
   public string name {get; set;}
}

public class City
{
    public Guid cityId {get; set;}
    public string name (get; set;
}

I want to me able to do something like this:

City city = new City {
   name = "Seattle";
};
Update<City>(city);

Using a generic method like this:

public T Insert<T>(T entity) where T : class
{
   // Instead of using code like this for each entity type
   if (entity is City)
   {
       City cEntity = entity as City
       cEntity.cityId = Guid.NewGuid();
   }

   // I want to be able to do something generically like this
   entity.PrimaryKey = Guid.NewGuid();

   // Add
   this._db.Set<T>().Add(item);
}

Is this crazy or should I just be having the database automatically add a Guid into the table upon Insert?

Thanks.

You can use reflection to find out the member that either of Guid type or have KeyAttribute

var byType = entity.GetType().GetProperties().First(x => x.PropertyType == typeof(Guid));
//or
var byAtttribute = entity.GetType().GetProperties().First(x=>x.CustomAttributes.Any(a=>a.AttributeType.Name=="KeyAttribute"));

then set the value

byType.SetValue(entity, Guid.NewGuid());
//or
byAttribute.SetValue(entity, Guid.NewGuid());

but this is guaranteed to be slower, and unless you need to assign a predefined Guid for some reason, it's better to let the database handle it.

Create an interface for the id:

public interface IHasGuid
{
    Guid ID { get; set; }
}

Then let your classes implement that interface:

public class Person : IHasGuid
{
   [Key]
   [Required]
   public Guid ID {get; set;}
   public string name {get; set;}
}

public class City : IHasGuid
{
    public Guid ID {get; set;}
    public string name (get; set;
}

Then you can access the ID property wherever T is IHasGuid :

public T Insert<T>(T entity) where T : class, IHasGuid
{
   entity.ID = Guid.NewGuid();

   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM