Best way to override SaveChanges()

后端 未结 3 1138
-上瘾入骨i
-上瘾入骨i 2020-12-16 16:43

We have worked on a project for 1 month and there are 6 entities without any relationship with other entities. They are all simple entities.

We have created 6 diffe

3条回答
  •  再見小時候
    2020-12-16 17:05

    To 'override' SaveChanges without needing to create all that extra code, I wrapped it in its own extension method. i.e.

    public static int SaveChangesWrapped(this MyDbContext db)
    {
        // do other things
    
        return db.SaveChanges();
    }
    

    or async...

    public static Task SaveChangesAsyncWrapped(this MyDbContext db)
    {
        // do other things
    
        return await db.SaveChangesAsync();
    }
    

    You can tweak it however you need, i.e. add other parameters, make it generic, etc. I may be missing something but this was enough for me to 'override' SaveChanges and cut down a whole lot of repeated code.

    Then anywhere in your code when you want to save, it's just:

    db.SaveChangesWrapped();
    
    //or
    
    await db.SaveChangedAsyncWrapped();
    

提交回复
热议问题