EF4.3知道上下文是否已成功插入实体 [英] EF4.3 know if context has successfully inserted entity

查看:135
本文介绍了EF4.3知道上下文是否已成功插入实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通用基类中具有以下方法:

I have the following method in a generic base class:

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

我的服务层使用Insert方法添加新记录.现在,我希望能够返回布尔值,以确保其正确插入.类似于以下内容:

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;
    }

有没有更优雅的方法呢?我完全不正确地处理它吗?我可以对Delete方法执行类似的操作,但是如何检查Update是否已成功执行?

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?

推荐答案

您不需要这样做.添加将成功或引发异常.它不会失败而不会失败地添加和返回.

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

此外,查询不会立即执行.它只是排队直到调用Commit(context.SaveChanges()).因此,您不知道实际的SQL是否会失败,直到稍后.

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.

这篇关于EF4.3知道上下文是否已成功插入实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆