【发布时间】:2019-04-15 04:53:55
【问题描述】:
我有 2 个表 Posts(ID,Title,DateTime,Body) & Tags(Id,Name) (和 PostsTags(PostID,TagID))和 c# 类: PostModel.cs:
public class PostModel
{
[Key]
[Required]
public int ID { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime DateTime { get; set; }
[Required]
public string Body { get; set; }
public List<TagModel> Tags { get; set; }
public List<CommentModel> Comments { get; set; }
public List<LikeModel> Likes { get; set; }
}
TagModel.cs:
public class TagModel
{
[Key]
[Required]
public int ID { get; set; }
public string Name { get; set; }
public List<PostModel> Posts { get; set; }
}
现在我想列出所有具有特定标签名称的帖子让我们说“偶数” 所以我要做的是首先获取甚至的TagID
query = "SELECT ID FROM Tags where [Name]='" + tagName + "'";
然后获取具有该标签的帖子
int tagId = int.Parse(dtTag.Rows[0][0].ToString());
query = "select [ID],[Title],[DateTime],[Body] from Posts inner join PostsTag on ID = PostID AND TagID =" + tagId;
现在在嵌套的 foreach 循环中我开始填充 Post 但问题是 我填写帖子及其标签->我必须在标签类中填写帖子->我必须在帖子类中添加标签->我必须在标签类中填写帖子等等。 如果我没有得到空引用。那么如何更改我的 c# 类以使其正常工作呢?
foreach (DataRow row1 in dtTag.Rows)
{
PostModel post = new PostModel();
post.Body = row1["Body"].ToString();
post.ID = int.Parse(row1["ID"].ToString());
post.DateTime = (DateTime)row1["DateTime"];
post.Title = row1["Title"].ToString();
int id1 = post.ID;
query = "SELECT [ID],[Name] FROM Tags as T inner join PostsTag as P on p.TagID=T.ID AND p.PostID=" + id1;
da = new SqlDataAdapter(query, sqlCon);
dtTag.Clear();
da.Fill(dtTag);
List<TagModel> tags = new List<TagModel>();
foreach (DataRow row in dtTag.Rows)
{
TagModel tag1 = new TagModel();
tag1.ID = int.Parse(row["ID"].ToString());
tag1.Name = row["Name"].ToString();
query = "select [ID],[Title],[DateTime],[Body] from Posts inner join PostsTag on ID = PostID AND TagID =" + tag1.ID;
// here I will need to fill tag1.Posts and after that post.tags and so on
tags.Add(tag1);
}
post.Tags = tags;
}
注意:我知道使用实体框架更容易,但我的老师要求使用手动 sql 查询。
【问题讨论】:
标签: c# asp.net sql-server asp.net-mvc