If you are using the Enterprise Library it is often better to set up a default connection in the configuration file:
<configuration>
<configSections>
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0,
Culture=neutral, PublicKeyToken=null"
requirePermission="false"/>
</configSections>
<dataConfiguration defaultDatabase="SiteSqlServer" />
<!-- Rest of your settings here, including your SiteSqlServer connection string -->
</configuration>
Now you don't need to look up the connection string - you can rely on the Enterprise library to get it for you:
public static void Insert(IEnumerble<int> skills, int resourceId)
{
// No dependency on SQL anymore - the connection string is found
// from the dataConfiguration section in your config file. If you change
// to another (supported) provider, you don't need to change this code.
Database db = DatabaseFactory.CreateDatabase();
// Add in your schema to the stored proc name (I've assumed dbo).
using (var cmd = db.GetStoredProcCommand("dbo.Insert_Skills_Resources"))
{
// This method populates the parameters collection of the DbCommand
// by interrogating the database about the command.
db.DiscoverParameters(cmd);
// As the parameters are now known, we can just set the value of
// them directly, no need specify direction or type etc.
cmd.Parameters["ResourceID"].Value = resourceId;
foreach (var skill in skills)
{
cmd.Parameters["SkillID"].Value = skill;
db.ExecuteNonQuery(cmd);
// Don't need to clear the parameters now.
}
// <Pointless try catch removed.>
}
}
EDIT:
Sorry, it's been a year or more since I used the Enterprise Library I can't remember whether you need the @ at the start of the parameter name or not - it might be cmd.Parameters["@SkillID"]
.
EDIT 2:
I remembered why I couldn't remember if you need the @ or not (if that makes sense). You do need the @ BUT, you should use the Database.BuildParameterName
method to create the parameter in the format the current provider expects - for sql server this is an @ symbol before the parameter name.
This is how you should do it:
cmd.Parameters[db.BuildParameterName("ResourceID")].Value = resourceId;
With this final correction the code is actually ignorant of the provider!
Database.BuildParameterName
to create it. \$\endgroup\$