1
我有一個叫做AddFoo(富富)方法C#實體框架,獲取插入ID(通用)
private int AddFoo(Foo foo)
{
Using (BarContext db = new BarContext())
{
db.Foos.Add(foo);
db.SaveChanges();
}
return foo.FooID;
}
我想使它更爲通用,以接受任何實體,並返回一個ID例如(粗糙,可能非功能只是爲了顯示這個想法:
private int Add(T entity)
{
Using (BarContect db = new BarContext())
{
// need to figure out how to find the appropriate set
DbSet dbSet = //Set Appropriate dbset based on entity type
dbSet.Add(entity);
db.SaveChanges();
}
return entity.PrimaryKeyValue; // this would be the integer value of the id
}
現在,我可以使用反射來找到標有屬性[關鍵]找出屬性在實體類包含了ID,但是我不我認爲這是最有效率的,我也可以用一些地圖方法來編碼,這樣我就可以找出DBSet要添加到什麼地方......但是我可以不要設想那裏已經沒有什麼東西可以以更高效的方式完成這兩項操作。
所以...我怎樣才能確定密鑰和它的價值,以及我怎樣才能找出什麼DbSet使用這個通用的東西?
UPDATE
基於下面的答案以及其他類似的帖子這是我落得這樣做......(非常簡單,只是結合了兩個答案)
private static int GetEntityKeyValue<T>(this T entity) where T : class
{
int ret = 0;
PropertyInfo key = typeof(T).GetProperties().FirstOrDefault(p => p.GetCustomAttributes(typeof(KeyAttribute), true).Length != 0);
if (key != null)
{
ret = (int)key.GetValue(entity, null);
}
return ret;
}
private static int Add<T>(T entity) where T : class
{
using (Foo db = new FooContext())
{
DbSet dbset = db.Set<T>();
dbset.Add(entity);
db.SaveChanges();
}
return entity.GetEntityKeyValue();
}
我想遠離反思...但是,呃。看起來就是這樣。
謝謝大家。
我只是打字這個確切的答案。 +1 – anaximander
PrimaryKeyValue,是否存在?我始終認爲獲得它的唯一方法是.EntityKey.EntitiyKeyValues(因爲SQL實體可以具有多個主鍵屬性...),除非您在所有表示IHasPKValue的實體上定義了一個接口,並強制您在那裏有PrimaryKeyValue .. 。,另外,int在這裏不是一個非常通用的解決方案... –
是的,我錯過了這部分的問題。我不認爲Add方法應該返回任何東西。 Id將被設置在實體上,呼叫者可以以這種方式訪問它。 – cadrell0