具有附加约束的导航属性

本文关键字:导航 属性 约束 | 更新日期: 2023-09-27 18:19:26

我是EF和CodeFirst的新手,我有以下(简化的)模型:

public class Comment
{
    public int ID {get; set;}
    public int SourceType {get; set;}
    public int SourceID {get; set;}
    public string Name {get; set;}
    public string Text {get; set;}
}
public class Photo
{
    public int ID {get; set;}
    public virtual ICollection<Comment> Comments {get; set;}
}
public class BlogPost
{
    public int ID {get; set;}
    public virtual ICollection<Comment> Comments {get; set;}
}

在我实际的数据库中,我只有这三个表。我的目标是有一个表"评论",存储用户为照片和博客文章发布的评论。Comment.SourceType字段应区分发布到照片(SourceType=1)或博客文章(SourceType=2)的评论,而Comment.SourceID字段告诉我来源的ID。

Photo photo = DbContext.Photos.Find(15); //some photo with ID 15
BlogPost blog = DbContext.BlogPost.Find(15); //some blog post, also with ID 15
Comment photoComment = new Comment();
photoComment.SourceType = 1; //photo
photoComment.SourceID = photo.ID;
photoComment.Name = "John";
photoComment.Text = "This is a very nice picture!";
Comment blogComment = new Comment();
blogComment.SourceType = 2; //blog post
blogComment.SourceID = blog.ID;
blogComment.Name = "Peter";
blogComment.Text = "An interesting blog post!";
DbContext.Comments.Add(photoComment);
DbContext.Comments.Add(blogComment);
DbContext.SaveChanges();
//...
Photo photoFromBefore = DbContext.Photos.Find(15);
foreach(Comment comment in photoFromBefore.Comments)
    Console.Write(comment.Name+"("+comment.SourceType+", "+comment.SourceID+"); ");
//Output will be: "John(1, 15); Peter(2, 15);"
//Desired output should be instead just "John(1, 15);"
//because Peter's comment actually belongs to blog post with
//the same ID but different "SourceType"-identifier in my database table.

我希望我想达到的目标能够清晰明了。基本上,我不想在我的网站上有多个表photo_commentsblogpost_comments等等。

我可以告诉EF只加载带有SourceType==1的评论(用于照片)吗?我是否可以使用某种类型的"约束"或"限制"来实现这一点?

具有附加约束的导航属性

您应该能够在foreach语句中使用LINQ where子句。

foreach(Comment comment in photoFromBefore.Comments.Where(x=>x.SourceType == 2))

此外,查看代码,foreach上方的行是否为

IEnumerable<Photo> photoFromBefore = DbContext.Photos.First(15);