ASP.NET: Как создать соединение из web.config ConnectionString?

Если вы хотите отправить данные из одного в другой viewController, вот путь к этому:

Скажем, у нас есть viewControllers: viewControllerA и viewControllerB

Теперь в viewControllerB.h

@interface viewControllerB : UIViewController {

  NSString *string;
  NSArray *array;

}

- (id)initWithArray:(NSArray)a andString:(NSString)s;

В viewControllerB.m

#import "viewControllerB.h"

@implementation viewControllerB

- (id)initWithArray:(NSArray)a andString:(NSString)s {

   array = [[NSArray alloc] init];
   array = a;

   string = [[NSString alloc] init];
   string = s;

}

В viewControllerA.m

#import "viewControllerA.h"
#import "viewControllerB.h"

@implementation viewControllerA

- (void)someMethod {

  someArray = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
  someString = [NSString stringWithFormat:@"Hahahahaha"];

  viewControllerB *vc = [[viewControllerB alloc] initWithArray:someArray andString:someString];

  [self.navigationController pushViewController:vc animated:YES];
  [vc release];

}

Таким образом, вы можете передавать данные из viewControllerA в viewControllerB без установки какого-либо делегата. ;)

10
задан Ian Boyd 25 June 2009 в 20:26
поделиться

3 ответа

Если вы пойдете по этому маршруту, я думаю, вы захотите использовать класс DbProviderFactories, чтобы получить DbProviderFactory, который вы можете использовать для создания соединения. Я не пробовал этот код, но думаю, что он сработает. Возможно, вам потребуется найти имя поставщика с помощью метода GetFactoryClasses в классе DbProviderFactories и использовать InvariantName.

public DbConnection GetConnection(String connectionName)
{
   //Get the connection string info from web.config
   ConnectionStringSettings cs= 
         ConfigurationManager.ConnectionStrings[connectionName];

   //documented to return null if it couldn't be found
   if (cs == null)
      throw new ConfigurationErrorsException("Invalid connection name \""+connectionName+"\"");

   //Get the factory for the given provider (e.g. "System.Data.SqlClient")
   DbProviderFactory factory = 
         DbProviderFactories.GetFactory(cs.ProviderName);

   //Undefined behaviour if GetFactory couldn't find a provider.
   //Defensive test for null factory anyway
   if (factory == null)
      throw new Exception("Could not obtain factory for provider \""+cs.ProviderName+"\"");

   //Have the factory give us the right connection object      
   DbConnection conn = factory.CreateConnection();

   //Undefined behaviour if CreateConnection failed
   //Defensive test for null connection anyway
   if (conn == null)
      throw new Exception("Could not obtain connection from factory");

   //Knowing the connection string, open the connection
   conn.ConnectionString = cs.ConnectionString;
   conn.Open()

   return conn;
}
17
ответ дан 3 December 2019 в 21:22
поделиться

Просмотрите этот блог Хансельмана о добавлении пользовательских типов сборки для разных имен строк подключения. Похоже, это может соответствовать тому, что вы хотите выполнить, иначе, чем использование типы провайдеров.

0
ответ дан 3 December 2019 в 21:22
поделиться

Если providerName для конкретного имени соединения (dev, test, prod) никогда не меняется, почему вы не можете переключить параметр connectionName для своего метода и установить таким образом экземпляр providerName?

0
ответ дан 3 December 2019 в 21:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: