Exemplo n.º 1
0
        /// <summary>
        /// Gets a SQL Local DB instance with the specified name if it exists, otherwise a new instance with the specified name is created.
        /// </summary>
        /// <param name="api">The <see cref="ISqlLocalDbApi"/> to use to get or create the instance.</param>
        /// <param name="instanceName">The name of the SQL Server LocalDB instance to get or create.</param>
        /// <returns>
        /// A SQL Local DB instance with the name specified by <paramref name="instanceName"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="api"/> or <paramref name="instanceName"/> is <see langword="null"/>.
        /// </exception>
        public static ISqlLocalDbInstanceInfo GetOrCreateInstance(this ISqlLocalDbApi api, string instanceName)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }

            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            // Instance names in SQL Local DB are case-insensitive
            if (string.Equals(api.DefaultInstanceName, instanceName, StringComparison.OrdinalIgnoreCase) ||
                SqlLocalDbApi.IsDefaultInstanceName(instanceName))
            {
                // The default instance is always listed, even if it does not exist,
                // so need to query that separately to verify whether to get or create.
                ISqlLocalDbInstanceInfo info = api.GetInstanceInfo(instanceName);

                if (info != null)
                {
                    // If it exists (or it's a default instance), we can't create
                    // it so just return the information about it immediately.
                    if (info.Exists || info.IsAutomatic)
                    {
                        return(info);
                    }
                }
            }

            if (api.InstanceExists(instanceName))
            {
                return(api.GetInstanceInfo(instanceName));
            }
            else
            {
                return(api.CreateInstance(instanceName, api.LatestVersion));
            }
        }