11

Вопрос по linq-to-sql, c# – LINQ to SQL вставки, если не существует

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

public static TEntity InsertIfNotExists<TEntity>
(
    DataContext db,
    Table<TEntity> table,
    Func<TEntity,bool> where,
    TEntity record
)
    where TEntity : class
{
    TEntity existing = table.SingleOrDefault<TEntity>(where);

    if (existing != null)
    {
        return existing; 
    }
    else
    {
        table.InsertOnSubmit(record);

        // Can't use table.Context.SubmitChanges()
        // 'cause it's read-only

        db.SubmitChanges();
    }

    return record;
}
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от core
  • Error: User Rate Limit Exceeded

    от core
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от core
  • 14

    Code:

    public static void InsertIfNotExists<TEntity>
                        (this Table<TEntity> table,
                         TEntity entity,
                         Expression<Func<TEntity,bool>> predicate)
        where TEntity : class
    { 
        if (!table.Any(predicate)) 
        {
            table.InsertOnSubmit(record);
            table.Context.SubmitChanges();
        }
     }
    
    
    table.InsertIfNotExists(entity, e=>e.BooleanProperty);
    

  • 4

    Error: User Rate Limit Exceeded

    public static void InsertIfNotExists<TEntity>
                        (this Table<TEntity> table
                         , TEntity entity
                        ) where TEntity : class
        {
            if (!table.Contains(entity))
            {
                table.InsertOnSubmit(entity);
    
            }
        }
    

  • 5

    Error: User Rate Limit Exceeded

    db.SubmitChanges()InsertIfNotExists<TEntity>

    InsertIfNotExists<TEntity>OnLoaded

    public partial class MyEntity
    {
        public bool IsLoaded { get; private set; }
        partial void OnLoaded()
        {
            IsLoaded = true;
        }
    }
    

    if (!record.IsLoaded)
        db.InsertOnSubmit(record);
    

  • 12

    Error: User Rate Limit Exceeded

    if (!Any()) { InsertOnSubmit(); }SubmitChangesSqlException

    using (var db = new DataContext()) {
    
        // Add the new (possibly duplicate) record to the data context here.
    
        try {
            db.SubmitChanges();
        } catch (SqlException ex) {
            const int violationOfPrimaryKeyContraint = 2627;
            const int violationOfUniqueConstraint = 2601;
            var duplicateRecordExceptionNumbers = new [] {
                violationOfPrimaryKeyContraint, violationOfUniqueConstraint
            };
            if (!duplicateRecordExceptionNumbers.Contains(ex.Number)) {
                throw;
            }
        }
    }