检查实体框架中是否存在记录

时间:2015-05-15 18:54:32

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

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

这是我的代码:

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?

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

1 个答案:

答案 0 :(得分:-1)