簡體   English   中英

檢查實體框架中是否存在記錄

[英]Check if a record exists in Entity Framework

我想知道數據庫中是否存在記錄以避免重復數據。

這是我的代碼:

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嗎?

我的問題是,每次添加新記錄時都必須保存更改嗎?

插入記錄時,EF6會自動填充對象的id屬性。

看到此如何獲取實體框架中插入的實體的ID?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM