Model for child table is always null in the partial view

痞子三分冷 提交于 2019-12-24 19:18:56

问题


In my ASP.NET Core 1.1, EF-Core 1.1 app, I'm displaying data in a parent view that has partial view. Scenario is similar to the following: one-to-many relationship between Customers and Orders table. User selects a customer from a dropdown in the Parent View that has a partial view that displays corresponding orders for the selected customer. But, I'm always getting model passed to the Partial view always null.

Question: What I may be missing here?

Note: By placing breakpoints, I've verified that the controller below is correctly sending the selected customer's record to the Parent View, and I've also checked in Db that that customer has corresponding order records in orders table.

Parent:

public class Customer
{
    [Key]
    public int CustomerId{ get; set; }
    public string Name { get; set; }
    ....
    ....
    public Order order { get; set; }
}

Child:

public class Order
{
    [Key]
    public int OrderId{ get; set; }
    public float Price { get; set; }
    ....
    ....
    public int? CustomerId { get; set; }
    public Customer customer{ get; set; }
}

Controller:

....
....
Customer mycustomer = _context.Customer.Where(c=> c.CustomerId== selectedId).SingleOrDefault();
....
....
return View(mycustomer);

Parent View:

@model MyProj.Models.Customer

....
@Html.Partial("Partial_orders", Model.order)
....

Partial View:

@model MyProj.Models.Order

....
<div>@Model.CustomerId<div>
....

回答1:


When you never load the Order, it can't be displayed.

EntityFramework Core do not support lazy loading yet. So when you call

Customer mycustomer = _context.Customer
   .Where(c=> c.CustomerId== selectedId).SingleOrDefault();

only customer will loaded. You have to eager load it with .Include or using .Load

Customer mycustomer = _context.Customer
   .Include(c => c.order) // Add this line to tell EF Core to load orders too
   .Where(c=> c.CustomerId== selectedId).SingleOrDefault();

Or alternatively:

Customer mycustomer = _context.Customer
   .Where(c=> c.CustomerId== selectedId).SingleOrDefault();

// do explicit loading async
await _context.Entry(mycustomer)
    .Reference(c => c.order)
    .LoadAsync();
// do explicit loading sync
_context.Entry(mycustomer)
    .Reference(c => c.order)
    .Load();


来源:https://stackoverflow.com/questions/44223233/model-for-child-table-is-always-null-in-the-partial-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!