简体   繁体   中英

c# Type Inference

I have an ECMContext class that inherits from DbContext. Within ECMContext there is a property MlaArticles which is DbSet<MlaArticle> where MlaArticle is inherited from WebObject . I have created a generic method that accepts an argument of type 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? 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:

try { db.SaveChanges(); }
catch
{
    db.Set<T>().Remove(obj);
}

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM