简体   繁体   中英

Check if a record exists in Entity Framework

I want to know if a record exists in a database to avoid duplicate data.

Here is my code:

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

This is inside a foreach loop

Function Create :

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

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

    return result;
}

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

The table has an identity column, so if I add the entity, I suppose I will have the id that is assigned right?

My question is, do I have to save changes every time I add a new record?

EF6 will automatically fill the id property of your object when you insert a record.

see this How can I get Id of inserted entity in Entity framework?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM