可能重复:
将 List<contacts> 插入表
我List<Contacts>
想遍历该列表以使用存储过程添加到数据库中。但我的foreach
循环只会在列表中插入第一个联系人。如何让它调用存储过程来插入所有联系人?
private static bool Insert_company_contacts(int companyID, List<Contacts> contacts)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// Set the stored procedure name
comm.CommandText = "AddContacts";
// Company Info
foreach (var c in contacts)
{
// create new parameter @LabelContactTypeID
DbParameter param = comm.CreateParameter();
param.ParameterName = "@CompanyID";
param.Value = companyID;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create new parameter @LabelContactTypeID
param = comm.CreateParameter();
param.ParameterName = "@LabelContactTypeID";
param.Value = c.LabelContactTypeID;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create new parameter @ContactDetails
param = comm.CreateParameter();
param.ParameterName = "@ContactDetails";
param.Value = c.ContactDetail;
param.DbType = DbType.StringFixedLength;
comm.Parameters.Add(param);
// create new parameter @Status
param = comm.CreateParameter();
param.ParameterName = "@Status";
param.Value = c.Status;
param.DbType = DbType.Boolean;
comm.Parameters.Add(param);
// create new parameter @Notes
param = comm.CreateParameter();
param.ParameterName = "@Notes";
param.Value = c.Notes;
param.DbType = DbType.StringFixedLength;
comm.Parameters.Add(param);
try
{
if (GenericDataAccess.ExecuteNonQuery(comm) == -1)
return false;
}
catch
{
return false;
}
}
return true;
}