0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
German Ortiz
  • 619
  • 1
  • 5
  • 8
  • 2
    Keep in mind that it's always possible for a new item to be added immediately after you do such a check, so it doesn't actually mean it's safe for you to add a new item without causing duplicates. Because of this such operations really need to be managed by the database, not the client. – Servy May 15 '15 at 19:00
  • So, to be sure of the id i have to save changes and then retrive the record? – German Ortiz May 15 '15 at 20:06

1 Answers1

-1

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?

Community
  • 1
  • 1
Alex Stephens
  • 3,017
  • 1
  • 36
  • 41