繁体   English   中英

没有实体框架外键关系的ASP.NET MVC

[英]Asp.net mvc without entity framework foreign key relationships

我有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,但是问题是我填充了Post及其标签->我将不得不在标签类中填充帖子->我将必须在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查询。

最简单的解决方案是将列表保留在Post或Tag上,无论您将哪个作为主要对象。 我会认为带有标签列表的帖子(尽管根据使用情况可能会相反)。

附带说明,您应该使用参数化的sql。 最好不要因为风险sql注入攻击而直接向sql添加参数。

https://docs.microsoft.com/zh-cn/dotnet/api/system.data.sqlclient.sqlparameter?view=netframework-4.7.2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM