EF4.3 know if context has successfully inserted entity

狂风中的少年 提交于 2019-12-11 11:05:24

问题


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.



来源:https://stackoverflow.com/questions/10263973/ef4-3-know-if-context-has-successfully-inserted-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!