【问题标题】:Check if a record exists in Entity Framework检查实体框架中是否存在记录
【发布时间】:2015-05-15 18:54:31
【问题描述】:

我想知道数据库中是否存在记录以避免重复数据。

这是我的代码:

var cliente = rClientes.Retrive(c => c.Cliente == cli);

if (cliente == null)
{
    var newCliente = new Entities.Clientes { Cliente = cli, PuntoReorden = 0 };
    cliente = rClientes.Create(newCliente);
    cliente = rClientes.Retrive(c => c.Cliente == cli);
}

这是在 foreach 循环中

函数Create

public TEntity Create(TEntity toCreate)
{
    TEntity result = null;

    try
    {
       EntitySet.Add(toCreate);
       result = toCreate;
    }
    catch (Exception ex) { throw ex; }

    return result;
}

函数Retrieve

public TEntity Retrieve(System.Linq.Expressions.Expression<Func<TEntity, bool>> criteria)
{
            TEntity result = null;

            try
            {
                result = EntitySet.FirstOrDefault(criteria);
            }
            catch (Exception ex) { throw ex; }

            return result;
}

表有一个标识列,所以如果我添加实体,我想我会有分配的 id 对吗?

我的问题是,每次添加新记录时都必须保存更改吗?

【问题讨论】:

  • 请记住,在您进行此类检查后,始终可以立即添加新项目,因此这实际上并不意味着您可以安全地添加新项目而不会导致重复。因此,此类操作确实需要由数据库而不是客户端来管理。
  • 那么,为了确定 id 我必须保存更改然后检索记录?

标签: c# entity-framework entity-framework-6


【解决方案1】:

EF6 会在您插入记录时自动填充对象的 id 属性。

看到这个How can I get Id of inserted entity in Entity framework?

【讨论】:

    猜你喜欢
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多