"The INSERT statement conflicted with the FOREIGN KEY" exception downs full system for all users

I have an asp.net mvc web application where I am getting

"The INSERT statement conflicted with the FOREIGN KEY"

This is not the main problem. I know why I am getting this exception. but the problem is it downs the full system for all users.

My Repository Interface:

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "");
    TEntity GetByID(int id);
    int Insert(TEntity entity);
    int Delete(int id);
    int Delete(TEntity entityToDelete);
    int Update(TEntity entityToUpdate);
    DbRawSqlQuery<TEntity> SQLQuery<TEntity>(string sql, params object[] parameters);
    int Save();
}

Repository Implementation:

public class Repository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class
{
    internal DbContext context;
    internal DbSet<TEntity> dbSet;

    public Repository(DbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {

        try
        {
            IQueryable<TEntity> query = dbSet.AsNoTracking();

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }
            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }
        catch (Exception)
        {
            return null;
        }
    }


    public virtual TEntity GetByID(int id)
    {
        try
        {
            return dbSet.Find(id);
        }
        catch (Exception)
        {
            return null;
        }

    }

    public virtual int Insert(TEntity entity)
    {
        try
        {
            dbSet.Add(entity);
            return 1;
        }
        catch (Exception ex)
        {
            return 0;
        }

    }

    public virtual int Delete(int id)
    {
        try
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
            return 1;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    public virtual int Delete(TEntity entityToDelete)
    {
        try
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
            return 1;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    public virtual int Update(TEntity entityToUpdate)
    {
        try
        {
            context.Set<TEntity>().AddOrUpdate(entityToUpdate);
            return 1;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    public DbRawSqlQuery<TEntity> SQLQuery<TEntity>(string sql, params object[] parameters)
    {
        try

        {
            var result = context.Database.SqlQuery<TEntity>(sql, parameters);
            return result;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    public int Save()
    {            
        try
        {
            context.SaveChanges();
            return 1;
        }
        catch (Exception ex)
        {
            //foreach (var entry in context.ChangeTracker.Entries())
            //{
            //    switch (entry.State)
            //    {
            //        case EntityState.Modified:
            //        case EntityState.Deleted:
            //            entry.State = EntityState.Modified; //Revert changes made to deleted entity.
            //            entry.State = EntityState.Unchanged;
            //            break;
            //        case EntityState.Added:
            //            entry.State = EntityState.Detached;
            //            break;
            //    }
            //}
            //return 0;
            throw ex;
        }
        //}
    }

    #region Disposal Methods

    // Dispose Methods

    private bool _disposed;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~Repository()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
        {
            // free other managed objects that implement
            // IDisposable only
        }

        // release any unmanaged objects
        // set the object references to null

        _disposed = true;
    }

    #endregion
}

Dependency Injection Class:

 private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();

        container.RegisterType(typeof(IRepository<>), typeof(Repository<>), new InjectionConstructor(new DbContext("PLLEntities")));


        container.RegisterType(typeof(IBaseService<>), typeof(BaseService<>));

        container.RegisterType<IErrorEngine, ErrorEngine>();
        container.RegisterType<ILoggingEngine, LoggingEngine>();
        container.RegisterType<IIdentityManager, IdentityManager>();

Can't figure it out where is the main issue is.

1 answer

  • answered 2018-07-11 08:11 Murat Yıldız

    The problem is most probably related to missing Primary Key definition. Check the related entity and be sure that you defined primary key using [Key] attribute in the entity class. Otherwise you encounter "The INSERT statement conflicted with the FOREIGN KEY constraint ..." error.

    public class YourEntity
    {
        [Key]
        public int Id { get; set; }
    
        //other properties
    }
    

    Hope this helps...