[英]MVC Linq query returning an inherited Entity's ID, but the Entity is null. How do I .Include() TPH members?
I have an MVC C# application using Razor Views. 我有一个使用Razor Views的MVC C#应用程序。 I have just implemented Table-Per-Hierarchy (TPH) and have run into an issue where I cannot .Include() the inherited Entity. 我刚刚实现了按层次结构表(TPH),并且遇到了无法.Include()继承的实体的问题。
@Html.DisplayFor(model => model.FundingOpportunity.FundingProgram.FundingAgency.Name)
When I attempt to show the contents of FundingAgency, it is always null. 当我尝试显示FundingAgency的内容时,它始终为null。 I can also modify the controller to .include FundingAgency, but it still comes up null. 我还可以将控制器修改为.include FundingAgency,但它仍然为null。
// GET: /Project/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var projectList = db
.Projects
.Include(p => p.FundingOpportunity)
.Include(p => p.FundingOpportunity.FundingProgram)
.Include(p => p.FundingOpportunity.FundingProgram.FundingAgency);
Project project = projectList.Where(p => p.ID == id).First();
if (project == null)
{
return HttpNotFound();
}
return View(project);
}
Here I have modified the Project Controller to .Include the FundingAgency. 在这里,我已将项目控制器修改为。包括FundingAgency。 You can see how the FundingAgencyID has a value and that value exists in the database, but the link to the FundingAgency Entity is not there. 您可以看到FundingAgencyID如何具有一个值,并且该值存在于数据库中,但是不存在指向FundingAgency实体的链接。 This is only happening with Table-Per-Hierarchy (TPH) items. 这仅在逐层表(TPH)项中发生。
You can try as shown below. 您可以尝试如下所示。
Program program = db.Programs.Where(X => X.ID == id)
.Include(p => p.Agency)
.First();
I think the problem is in this line: 我认为问题出在这一行:
public class Agency : Contact
{
--> public virtual ICollection<Program> Programs { get; set; }
}
It should be: 它应该是:
public virtual ICollection<FundingProgram> Programs {get; set;}
In addition to this, this line of code might be wrong: 除此之外,这行代码可能是错误的:
Program program = programs.Where(X => X.ID == id).First();
if (project == null) // Where does your project come from? Did you mean program?
{
return HttpNotFound();
}
I will post my solution for those searching in the future for a similar issue. 我将为以后搜寻类似问题的人发布解决方案。
During the Table-Per-Hierarchy (TPH) migration, the seed/migration file order was moved and this caused the SQL query to return the correct row, then check the Discriminator and that check failed, so it returned null. 在逐层表(TPH)迁移期间,种子/迁移文件的顺序已移动,这导致SQL查询返回正确的行,然后检查Discriminator,并且该检查失败,因此返回null。 This was deceptive because when you step through the process, the ID was not null and that row on the table contained data. 这具有欺骗性,因为当您逐步执行该过程时,该ID不为null,并且表上的该行包含数据。
I updated the seed files so that the correct ID range was attached to FundingOpportunity. 我更新了种子文件,以便将正确的ID范围附加到FundingOpportunity。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.