简体   繁体   English

数据库添加到实体框架核心后,子模型列表为空

[英]Child Model List is Empty after DB Add in Entity Framework Core

So I am trying out Entity Framework Core, and am having trouble with my first pair of relational Models. 所以我正在尝试实体框架核心,我的第一对关系模型遇到了麻烦。 I'm trying to use conventions to form the relationship, as follows: 我正在尝试使用约定来形成关系,如下所示:

The principal entity, with conventional principal key (Id) and collection navigation property (the list of Locations): 主体实体,具有传统的主键(Id)和集合导航属性(位置列表):

public class Site
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int LocationCount { get; set; } = 1;
    public List<Location> Locations { get; set; } = new List<Location>();
}

The dependent entity, with conventional foreign key (SiteId) and reference navigation property (Site): 依赖实体,具有传统外键(SiteId)和引用导航属性(站点):

public class Location
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    public Site Site { get; set; }
    public int AreaCount { get; set; } = 1;
    public Location(Site site) { SiteId = site.Id; }
}

And since I want every Site to already have at least one location, I put this in the Create action of the SiteController, in an attempt to create the dependents along with the principal: 由于我希望每个站点至少有一个位置,我将其放在SiteController的Create操作中,以尝试创建依赖项和主体:

[HttpPost]
public IActionResult Create(Site site)
{
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(site));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}

However, on the Details view, when I try to display the Locations that were created, the list is always empty: 但是,在“详细信息”视图中,当我尝试显示已创建的位置时,列表始终为空:

<h2>@Model.Locations.Count Locations</h2>    
@foreach (Location l in Model.Locations)
{
    <div class="row">
        <div class="col-sm-12">@l.Id</div>
    </div>
}

Just results in: 结果如下:

0 Locations

Thank you in advance for any help explaining what I've missed! 提前感谢您提供帮助,解释我错过的内容!

Edit: By request, here is the body of the Details action in the Site Controller, which gets the Model data for the Details View: 编辑:根据请求,这里是站点控制器中详细信息操作的主体,它获取详细信息视图的模型数据:

public IActionResult Details(string name)
{
    var model = _context.Sites.FirstOrDefault(a => a.Name == name);
    if (model == null) model = new Site();
    return View(model);
}

Also, per one suggestion, I have fixed the problem of setting the Location.SiteId before Site.Id has a value, since the Id isn't automatically generated on the Site until after SaveChanges() is called. 另外,根据一个建议,我已经解决了在Site.Id之前设置Location.SiteId的问题,因为在调用SaveChanges()之前,不会在网站上自动生成Id。 Unfortunately, the result (empty Locations list) is still the same: 不幸的是,结果(空位置列表)仍然是相同的:

[HttpPost]
public IActionResult Create(Site site)
{
    int nextsiteid = _context.Sites.Count() + 1;
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(siteid));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}

And changed the Location constructor to use the Id instead of the instance: 并将Location构造函数更改为使用Id而不是实例:

public Location(int siteid) { SiteId = siteid; }

Thanks in advance for any further suggestions! 提前感谢任何进一步的建议!

I'm just transcribing the answer I was given, which was provided in the comments of the original post, so that it can easily be found by anyone reading the post. 我只是在转录我给出的答案,这是在原帖的评论中提供的,所以任何阅读帖子的人都可以轻松找到答案。

The issue was, quite simply, that EF Core does not yet support lazy loading. 问题很简单,EF Core还不支持延迟加载。 So when the Site entity is populated, it doesn't lazily load the list of dependent locations into the collection navigation property. 因此,当填充Site实体时,它不会懒惰地将依赖位置列表加载到集合导航属性中。

The fix is to use eager loading, by way of: 修复是使用预先加载,通过以下方式:

var model = _context.Sites.Include(s => s.Locations).FirstOrDefault(a => a.Name == name);

When loading the Model data of the Site to provide to the View. 加载站点的模型数据以提供给视图时。

Thanks for the solution, Ivan! 谢谢你的解决方案,伊万!

if the Lazy Loading is true. 如果延迟加载是真的。 No need to loop over or navigate its child. 无需循环或导航其子项。 its will save your parent and as well its child. 它将拯救你的父母以及它的孩子。 make sure are you getting parents and its child 确保你得到父母及其孩子

[HttpPost]
public IActionResult Create(Site site)
{  // debug here are you getting parent & its child ?
_context.Sites.Add(site);
   // for (int i = 0; i < site.LocationCount; i++)  // No need of it
   // _context.Locations.Add(new Location(site));   // No need of it
_context.SaveChanges();
return RedirectToAction("Details", new { Name = site.Name });
}

Updated: if these two tables are linked with each other & you are manually trying to add location table . 更新:如果这两个表相互链接,并且您手动尝试添加位置表。 Let me give you a simple , hope this will help you 让我给你一个简单的,希望这会对你有所帮助

[HttpPost]
public IActionResult Create(Site site)
{  // debug here are you getting parent & its child ?
_context.Sites.Add(site);
   // get the last added site id

   int? maxId=
  _context.Sites.orderbyDecending(x=>x.SiteId).FirstorDefault(x=>x.SiteId);// may be in this line typing mistake , you change it according to linq
    foreach(var i in site.Location) 
    {
      // in this loop traverse the child array and override the foreign key id with last added id
       i.SiteId =maxId;
      _context.Locations.Add(i);
    }

_context.SaveChanges();
return RedirectToAction("Details", new { Name = site.Name });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .net core 2.0实体框架-在数据库级别添加表关系并更新模型 - .net core 2.0 Entity Framework - Add table relationship at db level and update model Entity Framework Core - 从现有数据库创建模型后尝试添加迁移时出错 - Entity Framework Core - Error when trying to Add Migration after creating Model from existing database 实体框架核心:将具有列表的对象添加到DbContext会导致列表为空 - Entity Framework Core: Adding an object with a List to a DbContext results in an empty List 实体框架核心 - 无法添加子记录 - Entity Framework Core - Can't Add Child records 如何使用 Entity Framework Core 中的另一个对象更新子列表 - How to update child list with another object in Entity Framework Core .NET Core 2.2 上的实体框架 6 - 一对多返回空列表 - Entity Framework 6 on .NET Core 2.2 - one to many return empty list 实体框架为唯一一个子模型添加区分列 - Entity Framework Add Discriminator Column for Only One Child Model Entity Framework Core DB先行,如何在不同的C#核心项目中添加实体关联 - Entity Framework Core DB first, How to add an entity association in different C# core projects 实体框架 | 将实体添加到数据库中,其中包含其他实体 - Entity Framework | Add entity to DB with other entity in it Entity Framework Core - 加载子实体 - Entity Framework Core - load child entity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM