【发布时间】:2012-01-04 02:18:05
【问题描述】:
我是 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;}
}
在我的实际数据库中,我只有这三个表。
我的目标是有一个表“cmets”,它存储 cmets 用户发布的照片和博客帖子。 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_comments、blogpost_comments 等用于我网站上可以评论的所有内容。
我能否以某种方式告诉 EF 仅加载带有 SourceType==1 的 cmets(用于照片)?我可以使用某种“约束”或“限制”来实现这一目标吗?
【问题讨论】:
标签: c# asp.net-mvc entity-framework ef-code-first