[英]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:有没有一种方法可以通用地标识主键(始终为单列)并在通用 Insert 方法中分配 Guid:
For example I have who dbSet classes.例如我有谁 dbSet 类。 Both have a single-field primary key of type Guid:
两者都有一个 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?这是疯狂的还是我应该让数据库在插入时自动将 Guid 添加到表中?
Thanks.谢谢。
You can use reflection to find out the member that either of Guid type or have KeyAttribute您可以使用反射来找出 Guid 类型或具有 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.但这保证会更慢,除非您出于某种原因需要分配预定义的 Guid,否则最好让数据库处理它。
Create an interface for the id:为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
:然后,您可以在
T
为IHasGuid
的任何地方访问ID
属性:
public T Insert<T>(T entity) where T : class, IHasGuid
{
entity.ID = Guid.NewGuid();
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.