2

I have the following method in a generic base class:

    public virtual void Insert(TEntity entity) {
        dbSet.Add(entity);
    }

My service layer uses the Insert method to add new records. Now I would like to be able to return a bool, to make sure that it inserted properly. Something like the following:

    public virtual int Count {
        get {
            return dbSet.Count();
        }
    }

    public virtual bool Insert(TEntity entity) {
        int count = this.Count;
        dbSet.Add(entity);

        return this.Count == count + 1;
    }

Is there a more elegant way to this? Am I approaching it completely incorrectly? I could do something similar for the Delete method, but how would I check if an Update has been performed successfully?

Mekswoll
  • 1,355
  • 3
  • 15
  • 35

1 Answers1

5

You don't need to do that. Add will either succeed or throw an exception. It cannot fail to add and return without throwing.

What's more, the query is not executed immediately. It's just queued until Commit (context.SaveChanges()) is called. So you don't know whether the actual SQL fails or not until later.

undefined
  • 33,537
  • 22
  • 129
  • 198
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Yup this is correct, SaveChanges will throw an exception if theres a DB error and Add will throw one if theres a context error, if you call add then SaveChanges with no error then it has successfully committed. – undefined Apr 22 '12 at 06:04
  • Ok, thank you for clarifying, I knew the actual SQL is only sent to the DB when I call the `SaveChanges()`. The best way to catch potential errors would then be to wrap the code that calls the `Insert` in a try catch block? – Mekswoll Apr 22 '12 at 14:51
  • @pEkvo - Virtually anything in .net can throw an exception in the right circumstances. You can't put a try/catch block around everything. Add throwing an exception is as likely as WriteLine throwing an exception (actually WriteLine is probably more likely). Honestly, this is something you don't need to worry about. – Erik Funkenbusch Apr 22 '12 at 18:28
  • @MystereMan, ok, thanks for expanding. I will leave it as it is then :-) – Mekswoll Apr 22 '12 at 18:59