简体   繁体   English

EF 5代码优先一对多导航属性空直到上下文被刷新

[英]EF 5 Code First One to Many Navigation Property Null Until Context is Refreshed

I've seen this question asked a few times but nothing solves my problem. 我已经看过几次这个问题,但没有解决我的问题。 I've created the most simple version I can: 我创建了最简单的版本:

public class Order
{
    public int OrderId { get; set; }
    public virtual List<Item> Items { get; set; } //One to many navigation property
}

public class Item
{
    public int ItemId { get; set; }
    public string Description { get; set; }
}

An order can have many items. 订单可以包含许多商品。 Simple. 简单。 Now to interact with the EF: 现在与EF互动:

using (var context = new TestContext())
{
    Order test = new Order();
    context.Orders.Add(test);
    context.SaveChanges();
    test.Items.Add(new Item {Description = "test"});  // no good - test.Items is null!
}

If I do this test.Items will be null and I cannot interact with it. 如果我做这个test.Items将为null,我无法与它进行交互。 However if I "refresh" the context all is well: 但是,如果我“刷新”上下文一切都很好:

using (var context = new TestContext())
{
    context.Orders.Add(new Order());
    context.SaveChanges();
}

using (var context = new TestContext())
{
    Order test = context.Orders.First();
    test.Items.Add(new Item {Description = "test"});  // Happy days - test.Items is NOT null :)
}

What am I missing? 我错过了什么? Or do I really need to get a fresh context every time I add an item with a one to many navigation property? 或者,每次添加具有一对多导航属性的项目时,我是否真的需要获得新的上下文?

Thanks in advance, oh wise guru of ether that know-eth the truth on this subject! 在此先感谢哦,以太明智的大师,知道这个主题的真相!

You need to create your entities using DbSet.Create() when using proxy entities (the default setting). 使用代理实体时,您需要使用DbSet.Create()创建实体(默认设置)。

Entity Framework Code First will create new classes at runtime that inherit from your model classes. 实体框架代码首先将在运行时创建从模型类继承的新类。 So you're not working with your Order class, but one that inherits from it. 所以你不是在使用Order类,而是继承它。 This new implementation will override your virtual navigation properties to implement additional features (such as lazy loading). 此新实现将覆盖您的虚拟导航属性以实现其他功能(例如延迟加载)。

The specific feature you require here is to notice when the collection has changed. 此处需要的特定功能是注意集合何时更改。 Your class does not provide any features like this (and should not), but the proxy class does. 您的类不提供此类(也不应该)的任何功能,但代理类可以。

Now when you new Class() your model object, it will be exactly your object. 现在,当您new Class()模型对象时,它将完全是您的对象。 It won't be the proxy entity and therefor won't have the additional features. 它不是代理实体,因此不具备附加功能。 DbSet.Create() on the other hand will return the proxy entity, upcasted to your class, so you're working with the proxy. DbSet.Create()将返回代理实体,并上传到您的类,因此您正在使用代理。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM