【问题标题】:Can't Lazy Load Entity After Saving New Record保存新记录后无法延迟加载实体
【发布时间】:2015-10-14 10:41:10
【问题描述】:

我在我的 MVC 3.0 应用程序中使用 Entity Framework 4.1。该应用程序是一种 n 层方法,我的 UI、模型、类、服务和存储库都放在一个解决方案中的单独项目中。我还使用了工作单元方法和依赖注入,因此,我无法访问 UI 中的 DbContext。

我有两个类,如下所示

public partial class Form
{
    public int id { get; set; }
    public int eventID { get; set; }
    public string sampleName { get; set; }

    public virtual Event GetEvent{ get; set; }
}

public partial class Event
{
    public int id { get; set; }
    public string eventName { get; set; }
}

然后在我的控制器中,我像这样添加一个 Form 类的实例

Form _form = new Form();
_form.eventID = 3;
_form.sampleName = "myString";

_formService.AddForm(_form);
_formService.SaveChanges(); //This calls the Unit of Work Commit

这工作并将记录插入数据库。但是然后在 SaveChanges() 调用下面的行中,我尝试像这样延迟加载相关的 Event 类

string _eventName = _form.GetEvent.eventName;

_form.GetEvent 的值始终为 NULL。 GetEvent 好像还没有加载。

谁能帮我解决这个问题?

提前致谢。

【问题讨论】:

    标签: c# entity-framework lazy-loading poco


    【解决方案1】:

    尝试将GetEvent 属性重命名为Event,以便EF 可以按照通常的conventions 推断外键关系(通过eventId)。

    【讨论】:

      【解决方案2】:

      你应该访问 Context ,并创建一个代理而不是 new Form ,这样你就可以在你访问 Context 的存储库中编写一个方法,并且返回类型是 Form 类。

      欲了解更多信息,请参阅Link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多