Reputation: 423
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.
Upvotes: 0
Views: 212
Reputation: 5719
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();
// ...
}
Upvotes: 0
Reputation: 5580
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.
Upvotes: 1