如何遍历复杂类型对象列表并传递给调用SQL存储过程的方法
如何遍历对象列表以便将所述对象传递给通过存储过程在SQL db中插入行的方法?
在这个问题的帮助下,我达到了这一点:
namespace NA.Controllers { public class NC : ApiController { [Route("AddNote")] [HttpPost] public HttpResponseMessage PostNote(List items) { //NoteJson deserializednote = JsonConvert.DeserializeObject(item); //Note notesdata = new Note(item); NotesAccept.Models.INoteRepository Repository = new NotesAccept.Models.NoteDataRepository(); foreach (Note item in items) { item = Repository.Add(item); } var response = Request.CreateResponse<List>(HttpStatusCode.OK, items); return response; } } }
但是现在我被卡住了,因为item=
现在是一个迭代变量,但我需要将它传递给一个方法:
namespace NA.Models { class NoteDataRepository : INoteRepository { public void Add(Note item) { if (item == null) { throw new ArgumentNullException("item"); } else { String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; SqlConnection con = new SqlConnection(strConnString); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "BL_IntegrationInsertNote"; cmd.Parameters.Add("@Client", SqlDbType.VarChar).Value = item.Client.Trim(); cmd.Parameters.Add("@Case", SqlDbType.VarChar).Value = item.Case; cmd.Parameters.Add("@Text", SqlDbType.VarChar).Value = item.Text.Trim(); cmd.Parameters.Add("@When", SqlDbType.DateTime).Value = item.Date; cmd.Parameters.Add("@Ext", SqlDbType.Bit).Value = item.Type; cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.Output; cmd.Connection = con; try { con.Open(); cmd.ExecuteNonQuery(); string id = cmd.Parameters["@return"].Value.ToString(); string lblMessage = null; lblMessage = "Record inserted successfully. ID = " + id; } catch (Exception ex) { throw ex; } finally { con.Close(); con.Dispose(); } } //return item; } IEnumerable INoteRepository.GetAll() { throw new NotImplementedException("getitems"); } } }
我仍然是C#的绿色新手,所以我不知道如何实现这一点,特别是因为整个解决方案仍然来自网络上的“复制和粘贴”,整个网络奇怪地专注于简单的循环类型。 如何用复杂的类型做到这一点?
正如其他问题所述,这是一个职业生死攸关的问题(我是一名数据库开发者,不是VS大师,特别是在两天两夜之后)。
-
您仍然忘记将该ID从DB分配给该项目。
-
你还有
return item;
在一个不返回任何内容的方法中(public void Add(Note item))。
所以只需删除该返回行。
-
并替换
item = Repository.Add(item);
只是
Repository.Add(item);
您可以将其作为xml传递并在sql存储过程中进行迭代并进行批量插入,或者如果您使用的sql和.net版本支持它,则可以使用表数据类型。
在foreach循环中尝试这个:
上述就是C#学习教程:如何遍历复杂类型对象列表并传递给调用SQL存储过程的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
var tempItem = item; tempItem = Repository.Add(tempItem);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/987656.html