我有一个项目,其中.Include
不会生成INNER JOIN,而INNER JOIN是在其他项目中使用相同的DbContext和代码生成的。
我正在使用EF Core Code-First。 DbContext通过NuGet与其他项目共享。
下面是有问题的两个类及其在DbContext中的配置:
[Table("Project", Schema = "ProjectManagement")]
public class AxosoftProject
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AxosoftId { get; set; }
public int? AxosoftParentId { get; set; }
public AxosoftProject AxosoftParent { get; set; }
public List<AxosoftProject> Children { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public string Description { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime UpdateDate { get; set; }
public ICollection<AxosoftItem> Items { get; set; }
}
[Table("Item", Schema = "ProjectManagement")]
public class AxosoftItem
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AxosoftId { get; set; }
public int AxosoftProjectId { get; set; }
public AxosoftProject AxosoftProject { get; set; }
public string Name { get; set; }
public string ItemType { get; set; }
public string SubItemType { get; set; }
public decimal PercentComplete { get; set; }
public DateTime UpdateDate { get; set; }
}
DbContext:
modelBuilder.Entity<AxosoftProject>().HasKey(x => x.AxosoftId);
modelBuilder.Entity<AxosoftProject>().HasOne(x => x.AxosoftParent).WithMany(x => x.Children);
modelBuilder.Entity<AxosoftProject>().HasMany(x => x.Items);
modelBuilder.Entity<AxosoftItem>().HasKey(x => x.AxosoftId);
modelBuilder.Entity<AxosoftItem>().HasOne(x => x.AxosoftProject);
用于查询所有项目及其项目的代码:
IMyEntities MyEntities = new MyEntities("Server=localhost;Database=MyEntities;Trusted_Connection=True;MultipleActiveResultSets=true");
var projects = MyEntities.AxosoftProjects.Include(x => x.Items).ToList();
var listwithitems = projects.Where(x => x.Items != null).ToList();
根据我在上面的代码中执行的项目,它将执行INNER JOIN或根本不执行INNER JOIN。我尝试删除上面的代码不执行INNER JOIN的整个项目,然后从存储库中克隆它以重新开始,但仍然没有INNER JOIN。
如何进一步调试?我怀疑无法正常运行的项目可能正在使用旧版本的DLL,即使它看起来指向的是正确的版本。
更新
为验证该包含确实不起作用,我进行了附加测试。如果我将AxosoftItems分别加载到DbContext中,则EF将填充每个AxosoftProject的Items集合。示例:
var projects = MyEntities.AxosoftProjects.Include(x => x.Items).ToList();
var listwithitems1 = projects.Where(x => x.Items != null).ToList(); // 0 items
var items = MyEntities.AxosoftItems.ToList();
var listwithitems2 = projects.Where(x => x.Items != null).ToList(); // 41 items
更新2
代码和对EF Core的引用放置在ASP.NET MVC项目中。将代码移至单独的类库可“解决”问题,不会忽略INNER JOIN,并且代码完全相同。我打算下载源代码并进行调试,以弄清楚为什么MVC项目中忽略了Include。