0

我正在使用以下代码生成一些 XML,但是我正在使用的系统在 EntityFramework 中使用手动加载而不是延迟加载。所以实际上,我必须调用 EnsureLoaded() 来明确说明需要加载哪些元素。问题是调用带有深度嵌套字段的 EnsureLoaded() 。这是我的代码;

public partial class Test
{
    public XElement ReturnDetails()
    {
        Test.DriverReference.EnsureLoaded();

        return new XElement("Test",
            new XAttribute("CarNum", CarNum),
            new XAttribute("Make", Make ?? string.Empty),
            new XAttribute("Model", Model ?? string.Empty),
            new XAttribute("Colour", Colour ?? string.Empty),
            new XElement("Drivers",
            from driver in Drivers
            select new XElement("Driver",
                new XAttribute("DriverNum", driver.DriverNum),
                new XAttribute("Notes", driver.Notes),
                new XElement("Routes"),
                from route in driver.Routes
                select new XElement("Route",
                    new XAttribute("Name", route.Name),
                    new XAttribute("Notes", route.Notes)
                ))));
    }
}

问题在于获取 Driver 的值,并在超出实体层次结构的三层时不断获取 NullReferenceExceptions。我想做的是以下内容;

public partial class Test
{
    public XElement ReturnDetails()
    {
        Test.DriverReference.EnsureLoaded();

        return new XElement("Test",
            new XAttribute("CarNum", CarNum),
            new XAttribute("Make", Make ?? string.Empty),
            new XAttribute("Model", Model ?? string.Empty),
            new XAttribute("Colour", Colour ?? string.Empty),
            new XElement("Drivers",
            from driver in Drivers.EnsureLoaded() *****
            select new XElement("Driver",
                new XAttribute("DriverNum", driver.DriverNum),
                new XAttribute("Notes", driver.Notes),
                new XElement("Routes"),
                from route in driver.Routes.EnsureLoaded() *****
                select new XElement("Route",
                    new XAttribute("Notes", route.Notes),
                    new XAttribute("Name", route.Name)
                ))));
    }
}
4

0 回答 0