【发布时间】:2020-05-13 22:59:40
【问题描述】:
有没有一种方法可以通用地标识主键(始终为单列)并在通用 Insert 方法中分配 Guid:
例如我有谁 dbSet 类。两者都有一个 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;
}
我希望我能够做这样的事情:
City city = new City {
name = "Seattle";
};
Update<City>(city);
使用这样的通用方法:
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);
}
这很疯狂还是我应该让数据库在插入时自动将 Guid 添加到表中?
谢谢。
【问题讨论】:
标签: c# asp.net entity-framework generics