Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

NopForeignKeyConvention.cs

using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Conventions;

namespace Nop.Data.Migrations;

/// 
/// Convention for the default naming of a foreign key
/// 
public class NopForeignKeyConvention : IForeignKeyConvention
{
    #region Fields

    protected readonly INopDataProvider _dataProvider;

    #endregion

    #region Ctor

    public NopForeignKeyConvention(INopDataProvider dataProvider)
    {
        _dataProvider = dataProvider;
    }

    #endregion

    #region Utilities

    /// 
    /// Gets the default name of a foreign key
    /// 
    /// The foreign key definition
    /// Name of a foreign key
    protected virtual string GetForeignKeyName(ForeignKeyDefinition foreignKey)
    {
        var foreignColumns = string.Join('_', foreignKey.ForeignColumns);
        var primaryColumns = string.Join('_', foreignKey.PrimaryColumns);

        var keyName = _dataProvider.CreateForeignKeyName(foreignKey.ForeignTable, foreignColumns, foreignKey.PrimaryTable, primaryColumns);

        return keyName;
    }

    #endregion

    #region Methods

    /// 
    /// Applies a convention to a FluentMigrator.Expressions.IForeignKeyExpression
    /// 
    /// The expression this convention should be applied to
    /// The same or a new expression. The underlying type must stay the same
    public IForeignKeyExpression Apply(IForeignKeyExpression expression)
    {
        if (string.IsNullOrEmpty(expression.ForeignKey.Name))
            expression.ForeignKey.Name = GetForeignKeyName(expression.ForeignKey);

        return expression;
    }

    #endregion
}