Пример #1
0
        /// <summary>
        /// Saves the data to the database if it has not already been added
        /// </summary>
        /// <typeparam name="T">The generic type</typeparam>
        /// <param name="data">The data is passed as a ref so that it will contain the database value if the object alreadt exists.
        /// This prevents adding duplicate values
        /// </param>
        /// <param name="checkIfExists">The predicate expression used in the LINQ query to check for existing values</param>
        private void AddToDb <T>(T data, Expression <Func <T, bool> > checkIfExists = default) where T : class
        {
            // Check if the entity already exists in the database
            Expression <Func <T, bool> > predicate = checkIfExists ?? (_ => false);

            var existingType = ctx.Set <T>().FirstOrDefault(predicate);

            if (existingType == null)
            {
                var result = ctx.Set <T>().Add(data);
                if (result.State == EntityState.Added)
                {
                    ctx.SaveChanges();
                }
            }
        }