EF4.3 know if context has successfully inserted en

2019-07-26 12:27发布

问题:

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?

回答1:

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.