插入一条数据并获得返回该数据的主键。
1 public int SendMessage(InternalMessage IM, string[] IMPStaffID)
2 {
3 //数据库连接属性 引用using System.Data.SqlClient;
4 using (SqlConnection IDbCon = new SqlConnection(ConfigureHelp.Connection))
5 {
6 //数据库连接
7 IDbCon.Open();
8 //开启事务。需引用using System.Data;
9 IDbTransaction _tran = IDbCon.BeginTransaction();
10
11 //OUTPUT INSERTED.IMID :返回插入这条数据的主键IMID。
12 string InsertIMsql = @"INSERT INTO InternalMessage(IMIsIncognito,IMType,IMObjectNum,IMContent,IMFile,IMIsLock,IMDelFlag,IMStaffID,IMDate) OUTPUT INSERTED.IMID VALUES(@IMIsIncognito,@IMType,@IMObjectNum,@IMContent,@IMFile,@IMIsLock,@IMDelFlag,@IMStaffID,@IMDate)";
13
14 string InsertIMPsql = @"INSERT INTO IMPermissions(IMPStaffID,InternalMessageID) VALUES(@IMPStaffID,@InternalMessageID)";
15 try
16 {
17 var IMID = IDbCon.ExecuteScalar<long>(InsertIMsql, IM,_tran);
18
19 //将数组循环添加到imp对象中
20 IList<IMPermissions> imp = new List<IMPermissions>();
21 for (int i = 0; i < IMPStaffID.Length; i++)
22 {
23 IMPermissions imps = new IMPermissions();
24 long tId = 0;
25 if (long.TryParse(IMPStaffID[i], out tId))
26 {
27 imps.IMPStaffID = tId;
28 imps.InternalMessageID = IMID;
29 imp.Add(imps);
30 };
31 }
32
33 if(IMID > 0)
34 {
35 //imp是个对象,同时插入多条数据
36 var IMPcount = IDbCon.Execute(InsertIMPsql, imp, _tran);
37 if(IMPcount >0)
38 {
39 _tran.Commit();
40 return 1;
41 }
42 }
43 _tran.Rollback();
44 return 0;
45
46 }
47 catch (Exception ex)
48 {
49 UtilityHelp.WriteLog(ex, ex.ToString());
50 return -1;
51 }
52 }
53 }