[英]c# Type Inference
I have an ECMContext class that inherits from DbContext. 我有一个继承自DbContext的ECMContext类。 Within ECMContext there is a property MlaArticles
which is DbSet<MlaArticle>
where MlaArticle
is inherited from WebObject
. 在ECMContext中有一个属性MlaArticles
,它是DbSet<MlaArticle>
,其中MlaArticle
继承自WebObject
。 I have created a generic method that accepts an argument of type WebObject. 我创建了一个接受WebObject类型参数的泛型方法。 The method tries to save changes to the db and if not, backs out the changes. 该方法尝试将更改保存到数据库,如果没有,则退出更改。
My question - since I already have db (which was already instantiated) and I know the type of WebObject
that is being passed ( MlaArticle
in this example), is there a way to refer to the DbSet collection db.MlaArticles
without passing an extra argument? 我的问题 - 因为我已经有db(已经实例化)并且我知道正在传递的WebObject
的类型(在这个例子中是MlaArticle
),有没有办法在不传递额外参数的情况下引用DbSet集合db.MlaArticles
? I know this is wrong but this exemplifies my question... 我知道这是错的,但这体现了我的问题......
protected ECMContext db;
void SaveChanges<T>(T obj) where T : WebObject
{
try { db.SaveChanges(); }
catch
{
db.MlaArticles.Remove(obj); //this is the original code
db.DbSet<T>.Remove(obj); //something like this is what I'd like to do
}
}
Can you use the Set<T>()
operation: 你可以使用Set<T>()
操作:
try { db.SaveChanges(); }
catch
{
db.Set<T>().Remove(obj);
}
? ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.