2010-03-13 23 views
3

有人可以告訴我如何防止此錯誤。具有相同密鑰的項目已被添加。使用同一個鍵的項目已被添加

// Failed to find a matching SessionFactory so make a new one. 
     if (sessionFactory == null) 
     { 
      Check.Require(File.Exists(sessionFactoryConfigPath), 
          "The config file at '" + sessionFactoryConfigPath + "' could not be found"); 

      Configuration cfg = new Configuration(); 
      cfg.Configure(sessionFactoryConfigPath); 

      /*MINE*/ 
      var persistenceModel = new PersistenceModel(); 
      persistenceModel.AddMappingsFromAssembly(Assembly.Load("EMedicine.Core")); 
      persistenceModel.Configure(cfg); 
      /*END_OF_MINE*/ 

      // Now that we have our Configuration object, create a new SessionFactory 
      sessionFactory = cfg.BuildSessionFactory(); 

      if (sessionFactory == null) 
      { 
       throw new InvalidOperationException("cfg.BuildSessionFactory() returned null."); 
      } 

      if (sessionFactoryConfigPath != null) sessionFactories.Add(sessionFactoryConfigPath, sessionFactory); 
     } 

錯誤是在這裏: 的sessionFactory = cfg.BuildSessionFactory();

+0

你有cfg.BuildSessionFactory()方法的來源嗎? – 2010-03-13 10:30:20

+0

沒有對不起,我不把它 – senzacionale 2010-03-13 11:31:51

回答

2

嘗試以下操作:

if (
    sessionFactoryConfigPath != null && 
    sessionFactories.ContainsKey(sessionFactoryConfigPath) 
) { 
    sessionFactory = cfg.BuildSessionFactory(); 

    if (sessionFactory == null) 
    { 
     throw new InvalidOperationException("cfg.BuildSessionFactory() returned null."); 
    } 

    sessionFactories.Add(sessionFactoryConfigPath, sessionFactory); 
} else (sessionFactoryConfigPath != null) { 
    sessionFactory = sessionFactories[sessionFactoryConfigPath]; 
} 
+0

THX你的答案,但現在我得到對象引用不設置到對象的實例在第二else語句 如果(攔截!= NULL) { 會話= GetSessionFactoryFor(sessionFactoryConfigPath)。的openSession(攔截); } else session = GetSessionFactoryFor(sessionFactoryConfigPath).OpenSession(); } – senzacionale 2010-03-13 10:51:10

+0

只需檢索現有的sessionFactory ...請參閱編輯。 (sessionFactoryConfigPath!= null) sessionFactory =(ISessionFactory)sessionFactories [sessionFactoryConfigPath];其中if(sessionFactoryConfigPath!= null) – AxelEckenberger 2010-03-13 10:53:08

+0

}但它是一樣的。如果if語句會像if(sessionFactoryConfigPath!= null &&!sessionFactories.ContainsValue(sessionFactory)) { – senzacionale 2010-03-13 11:15:50

0

這是解決好嗎?

try 
        { 
         // Now that we have our Configuration object, create a new SessionFactory 
         sessionFactory = cfg.BuildSessionFactory(); 

         if (sessionFactory == null) 
         { 
          throw new InvalidOperationException("cfg.BuildSessionFactory() returned null."); 
         } 

         if (sessionFactoryConfigPath != null) 
          sessionFactories.Add(sessionFactoryConfigPath, sessionFactory); 
        } 
        catch (Exception) 
        { 
         if (sessionFactoryConfigPath != null) 
          sessionFactory = (ISessionFactory) sessionFactories[sessionFactoryConfigPath]; 
        } 
相關問題