如何将此查询转换为内联sql或存储过程?
var a = from arow in context.post
where arow.post_id == id && arow.post_isdeleted == false
select new
{
arow.post_id,
PostComments = from c in context.comment
where c.CommentPostID == arow.post_id
select new
{
c.id,
c.title
}
}
List<PostType> pt;
foreach (var s in a)
{
pt = new PostType();
pt.PostID = s.post_id;
//how would I use ADO.NET to put this in a custom class?
foreach(var ctl in s.PostComments)
{
ctl.Title = ctl.title;
pt.CommentT.Add(ctl);
}
ptl.Add(pt);
}
一旦执行了内联查询,我如何将信息放入自定义类中? PostComments 是一个子查询 - 那么我如何使用ADO.NET将其放入自定义类?
答案 0 :(得分:1)
如果您的意思是Posts和PostComments表之间存在关系,并且两个表中都有重复的列,并且一条评论可能与多个帖子有关,那么 您可以轻松创建两个命令:
-Select * from Posts where post_Id = id AND IsDeleted = 0;
-Select * from Postcomments where id = cid;
然后在两个数据表上使用Sql Command Adapters执行它们。然后:
foreach(DataRow dr in PostsTable.Rows)
{
//Fill the Post Custom class
SecondTable.DefaultView.RowFilter = string.Format("PostID = {0}",dr["postID"]);
foreach(DataRow r in SecondTable.Rows)
{
//Fill the Comments Custom class
}
}
如果不是这种情况,那么您是否可以尝试澄清数据库结构?
答案 1 :(得分:1)
使用SQL事件探查器捕获生成的查询。复制到新的存储过程并修复输入参数。创建(保存)并使用它:)
答案 2 :(得分:1)
答案 3 :(得分:0)
我不能测试这个,但是有些东西:
SELECT
p.post_id
c.id,
c.title
FROM
post p
WHERE
p.id == 'id' and
isdeleted = false
INNER JOIN comment c ON c.commentpostid = p.post_id
我将关键字大写以提高可读性,但对于您正在使用的dbs,您可能需要更改它。
答案 4 :(得分:0)
select post_id, id, title from postcomments pc
where post_id = @id and exists(
select post_id form post p where p.post_id = pc.post_id and isdeleted = false
)
使用DataReader获取数据&amp;只需将其加载到包含自定义类的列表中