2012-01-04 36 views
0

我新的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_comments,blogpost_comments等等,可以在我的网站上发表评论。

我能以某种方式告诉EF仅加载与SourceType==1(对于照片)的评论吗?有什么类型的“约束”或“限制”我可以用来实现这一点?

回答

0

你应该可以在你的foreach语句中使用LINQ where子句。

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

而且,看代码,应该在foreach上面的线是

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

这就是我试图避免虽然:) EF的全部目的就是少做工作。我知道我可以手动加载评论,但是Photo.Comments是一个导航属性,当我调用它时,它会自动加载所有照片的评论。 另外,你对错误的代码是正确的。我有一个错误(“第一”而不是“查找”),我现在纠正。谢谢。 – 2012-01-04 11:35:34

+0

你的问题是照片和博客是两个不同的表格(对吧?)。由于它们是两个不同的表,它们将具有两组主键。因此 - 您可以使用Id 1创建博客,使用Id 1创建一张照片。EF无法知道基于该Id加载哪个注释,而无需在查找语句中指定where子句(sourcetype == x)。导航属性是FK的一个代码等价物 - 您可以将该值映射到表格a col x到表b col y。如果您试图避免使用where子句,则可以将源类型存储在照片和博客表中... – Tommy 2012-01-04 14:12:42

+0

是的,我意识到问题:)我试图弄清楚是否有办法使EF _know_加载哪条评论。例如使用Fluid API。使用'modelBuilder.Entity ().Property(p => p.Comments).HasCondition(c => c.SourceType == 1);'''和'modelBuilder.Entity (())替代'OnModelCreating(DbModelBuilder modelBuilder) ).Property(b => b.Comments).HasCondition(c => c.SourceType == 2);'。我只是在这里吐口水,但我想知道这样的事情是否可能? – 2012-01-04 20:58:44