在表中创建新记录,获取记录id并在第二个过程中使用
本文关键字:第二个 过程中 id 获取 创建 新记录 记录 | 更新日期: 2023-09-27 18:11:44
我有一个有点棘手的问题要问,但我会尽力的。
我有两个类:
- BlogPost
- BlogTag
BlogPost
有一个公共属性HashSet<BlogTag> Tags
,一个博客标签的集合,足够简单。我想要实现的是添加一个新的BlogPost
到我的表dbo。然后遍历标签的HashSet并更新一个单独的表dbo。例如,使用集合中的每个标签及其所属文章的ID。
我可以这样做:-
public static void AddPost(BlogPost post)
{
try
{
Database db = DatabaseFactory.CreateDatabase(Constants.Application.DatabaseName);
DbCommand cmd = db.GetStoredProcCommand("stp_BlogPost_Add");
db.AddInParameter(cmd, "post_title", DbType.String, post.Title);
db.AddInParameter(cmd, "author", DbType.String, post.Author);
db.AddInParameter(cmd, "date_created", DbType.DateTime, DateTime.Now);
db.AddInParameter(cmd, "post_content", DbType.String, post.Content);
//Snip...
//Insert tags
foreach(BlogTag tag in post.Tags)
{
AddNewTags(post.ID, tag.TagText);
}
db.ExecuteNonQuery(cmd);
}
catch (Exception ex)
{
Logging.LogError(ex);
throw;
}
}
然而,我似乎无法回避的问题是:
foreach(BlogTag tag in post.Tags)
{
AddNewTags(post.ID, tag.TagText);
}
只有当我们有post.ID
值时,上述操作才会起作用,但是,由于这是在AddPost
方法中运行的,此时ID仍将是默认的0
(记录的ID是表中的PK,并设置为自动递增)。
是否有一种方法可以将HashSet<BlogTags>
直接作为参数传递给存储过程(值得一提的是,我是一个完全的SQL新手),然后一旦stp_BlogPost_Add
过程运行,获得新创建的帖子的id并将值插入到BlogTags表中?
或者,除了上述方法之外,是否有更好的方法来实现我想要做的事情?我曾考虑简单地将标签存储为BlogPost表中的逗号分隔字符串,然后在需要时通过,
分割,但这似乎不那么干净。
如有任何建议,不胜感激
您不能将对象传递给存储过程,因为SQL引擎将不知道那是什么。您可以将XML字符串传递给它并对其进行操作。如果您将对象设置为可序列化的,则可以将其序列化为xml字符串并将其传入。它基本上是你的对象的XML表示。
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx