¿La mejor manera de comprobar si el objeto existe en Entity Framework?


¿Cuál es la mejor manera de comprobar si existe un objeto en la base de datos desde el punto de vista del rendimiento? Estoy usando Entity Framework 1.0 (ASP.NET 3.5 SP1).

Author: Alex Angas, 2009-11-26

7 answers

Si no desea ejecutar SQL directamente, la mejor manera es usar Any(). Esto se debe a que Any () volverá tan pronto como encuentre una coincidencia. Otra opción es Count(), pero esto podría necesitar comprobar cada fila antes de regresar.

Aquí hay un ejemplo de cómo usarlo:

if (context.MyEntity.Any(o => o.Id == idToMatch))
{
    // Match!
}

Y en vb.net

If context.MyEntity.Any(function(o) o.Id = idToMatch) Then
    ' Match!
End If
 194
Author: Alex Angas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-17 02:06:22

Desde un punto de vista de rendimiento, supongo que una consulta SQL directa usando el comando EXISTS sería apropiada. Vea aquí cómo ejecutar SQL directamente en Entity Framework: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

 7
Author: Konamiman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-26 08:48:24

Tuve algunos problemas con esto - mi EntityKey consta de tres propiedades (PK con 3 columnas) y no quería comprobar cada una de las columnas porque eso sería feo. Pensé en una solución que funcione todo el tiempo con todas las entidades.

Otra razón para esto es que no me gusta coger UpdateExceptions cada vez.

Se necesita un poco de reflexión para obtener los valores de las propiedades de la clave.

El código se implementa como una extensión para simplificar el uso como:

context.EntityExists<MyEntityType>(item);

Echa un vistazo:

public static bool EntityExists<T>(this ObjectContext context, T entity)
        where T : EntityObject
    {
        object value;
        var entityKeyValues = new List<KeyValuePair<string, object>>();
        var objectSet = context.CreateObjectSet<T>().EntitySet;
        foreach (var member in objectSet.ElementType.KeyMembers)
        {
            var info = entity.GetType().GetProperty(member.Name);
            var tempValue = info.GetValue(entity, null);
            var pair = new KeyValuePair<string, object>(member.Name, tempValue);
            entityKeyValues.Add(pair);
        }
        var key = new EntityKey(objectSet.EntityContainer.Name + "." + objectSet.Name, entityKeyValues);
        if (context.TryGetObjectByKey(key, out value))
        {
            return value != null;
        }
        return false;
    }
 4
Author: Sven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-17 08:10:08

Tuve que manejar un escenario en el que el porcentaje de duplicados que se proporcionaban en los nuevos registros de datos era muy alto, y se hacían miles de llamadas a la base de datos para verificar los duplicados (por lo que la CPU enviaba mucho tiempo al 100%). Al final decidí mantener los últimos 100.000 registros en caché en la memoria. De esta manera pude comprobar si había duplicados contra los registros almacenados en caché, que era extremadamente rápido en comparación con una consulta LINQ contra la base de datos SQL, y luego escribir cualquier genuinamente nuevo registros a la base de datos (así como agregarlos a la caché de datos, que también ordené y recorté para mantener su longitud manejable).

Tenga en cuenta que los datos sin procesar eran un archivo CSV que contenía muchos registros individuales que tenían que ser analizados. Los registros en cada archivo consecutivo (que llegó a una tasa de aproximadamente 1 cada 5 minutos) se superpusieron considerablemente, de ahí el alto porcentaje de duplicados.

En resumen, si tiene datos raw con marca de tiempo que vienen, más o menos en orden, la memoria caché puede ayudar con la comprobación de duplicación de registros.

 4
Author: ProfNimrod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-02 15:10:35

Sé que este es un hilo muy antiguo, pero en caso de que alguien como yo necesite esta solución, pero en VB.NET esto es lo que usé en base a las respuestas anteriores.

Private Function ValidateUniquePayroll(PropertyToCheck As String) As Boolean
    // Return true if Username is Unique
    Dim rtnValue = False
    Dim context = New CPMModel.CPMEntities
    If (context.Employees.Any()) Then ' Check if there are "any" records in the Employee table
        Dim employee = From c In context.Employees Select c.PayrollNumber ' Select just the PayrollNumber column to work with
        For Each item As Object In employee ' Loop through each employee in the Employees entity
            If (item = PropertyToCheck) Then ' Check if PayrollNumber in current row matches PropertyToCheck
                // Found a match, throw exception and return False
                rtnValue = False
                Exit For
            Else
                // No matches, return True (Unique)
                rtnValue = True
            End If
        Next
    Else
        // The is currently no employees in the person entity so return True (Unqiue)
        rtnValue = True
    End If
    Return rtnValue
End Function
 4
Author: Kevin Morrissey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-05 22:16:56

Solo compruebo si el objeto es nulo, funciona al 100% para mí

    try
    {
        var ID = Convert.ToInt32(Request.Params["ID"]);
        var Cert = (from cert in db.TblCompCertUploads where cert.CertID == ID select cert).FirstOrDefault();
        if (Cert != null)
        {
            db.TblCompCertUploads.DeleteObject(Cert);
            db.SaveChanges();
            ViewBag.Msg = "Deleted Successfully";
        }
        else
        {
            ViewBag.Msg = "Not Found !!";
        }                           
    }
    catch
    {
        ViewBag.Msg = "Something Went wrong";
    }
 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-14 05:40:37

¿por Qué no hacerlo?

var result= ctx.table.Where(x => x.UserName == "Value").FirstOrDefault();

if(result.field == value)
{
  // Match!
}
 0
Author: Matheus Miranda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-08 22:53:20