具有附加约束的导航属性

时间:2012-01-04 02:18:05

标签: c# asp.net-mvc entity-framework ef-code-first

我是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。 / p>

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的评论(对于照片)吗?我可以使用某种类型的“约束”或“限制”来实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

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

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

另外,看一下代码,foreach上面的行应该是

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