Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带有附加约束的导航属性_C#_Asp.net Mvc_Entity Framework_Ef Code First - Fatal编程技术网

C# 带有附加约束的导航属性

C# 带有附加约束的导航属性,c#,asp.net-mvc,entity-framework,ef-code-first,C#,Asp.net Mvc,Entity Framework,Ef Code First,我是EF和CodeFirst的新手,我有以下(简化)模型: 我希望我想要达到的目标是明确的。基本上,对于我的网站上可以评论的所有内容,我不想有多个表photo_comments,blogpost_comments等等 我是否可以告诉EF只加载SourceType==1(用于照片)的注释?是否有某种类型的“constraint”或“restriction”可以用来实现这一点?您应该能够在foreach语句中使用LINQ where子句 foreach(Comment comment in phot

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

我希望我想要达到的目标是明确的。基本上,对于我的网站上可以评论的所有内容,我不想有多个表
photo_comments
blogpost_comments
等等


我是否可以告诉EF只加载
SourceType==1
(用于照片)的注释?是否有某种类型的“constraint”或“restriction”可以用来实现这一点?

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

foreach(Comment comment in photoFromBefore.Comments.Where(x=>x.SourceType == 2))
另外,看看代码,foreach上面的行应该是

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

这正是我试图避免的:)EF的全部目的是减少工作量。我知道我可以手动加载评论,但是
Photo.comments
是一个导航属性,当我调用它时,它会自动加载该照片的所有评论。另外,关于错误的代码,您是对的。我有一个拼写错误(“First”而不是“Find”),我现在改正了。谢谢。你的问题是照片和博客是两个不同的表格(对吧?)。因为它们是两个不同的表,所以它们将有两组主键。所以-你可以有一个Id为1的博客和一张Id为1的照片。如果不在Find语句(sourcetype==x)中指定where子句,EF就无法知道基于该Id加载哪个注释。导航属性是相当于FK的代码-您可以将值从表A列x映射到表b列y。如果您试图避免where子句,可以将源类型存储在照片和博客表中…是的,我知道问题:)我正在尝试找出是否有方法让EF知道要加载哪个注释。例如,流体API。使用类似于
modelBuilder.Entity().Property(p=>p.Comments).HasCondition(c=>c.SourceType==1)的内容重写
OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity().Property(b=>b.Comments).HasCondition(c=>c.SourceType==2)。我只是说说而已,但我想知道这样的事情是否可能?
foreach(Comment comment in photoFromBefore.Comments.Where(x=>x.SourceType == 2))
IEnumerable<Photo> photoFromBefore = DbContext.Photos.First(15);