EF Core 3.1导航属性

时间:2020-09-17 02:15:17

标签: .net-core entity-framework-core

我想根据以下代码将数据库表与EF Core 3.1连接。 问题是ModellNavigation和ManufacturerNavigation返回的值为null。 我究竟做错了什么?请帮助我。

        public IEnumerable<ViewModel> GetAll()
        {
            List<ViewModel> models = new List<ViewModel>();
            foreach(Detail detail in _context.Detail)
            {
                ViewModel viewModel = new ViewModel
                {
                    ID = detail.DetailId,
                    Manufacturer = detail.ModellNavigation.ManufacturerNavigation.Name,
                    Modell = detail.ModellNavigation.Name,
                    Consumption = detail.Consumption,
                    Color = detail.Color,
                    Year = detail.Year,
                    Horsepower = detail.Horsepower
                };
                models.Add(viewModel);
            }
            return models;
        }

3 个答案:

答案 0 :(得分:0)

您需要在EntityFramework Configuration中定义Detail和ModelNavigation的关系,以便在访问细节模型时它将加载模型导航。 请检查此链接: https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

答案 1 :(得分:0)

在此代码段中,modell尽管使用延迟加载,但返回的值为null! 再次感谢您的帮助,我非常感谢! (请原谅我的英语,我不是本地人!)

[HttpGet]
        public IEnumerable<CarView> getAllCars()
        {
            List<CarView> carViews = new List<CarView>();
            foreach(Manufacturer manufacturer in _context.Manufacturer)
            {
                CarView car = new CarView();
                car.Manufacturer = manufacturer.Name;
                foreach(Modell modell in manufacturer.Modell)
                {
                    car.Modell = modell.Name;
                    foreach(Detail detail in modell.Details)
                    {
                        car.ID = detail.DetailId;
                        car.Consumption = detail.Consumption;
                        car.Color = detail.Color;
                        car.Year = detail.Year;
                        car.Horsepower = detail.Horsepower;
                    }
                }
                carViews.Add(car);
            }
            return carViews;
        }

答案 2 :(得分:0)

像您一样进行枚举将在每个循环中进行一次查询,并且如果还添加延迟加载,它将产生更多的查询和复杂性。

您应该直接在EF Core中投影查询,这样只会对数据库生成一个查询。

public IEnumerable<ViewModel> GetAll()
{
    return _context.Detail.Select(
        d => new ViewModel()
        {
            ID = detail.DetailId,
            Manufacturer = detail.ModellNavigation.ManufacturerNavigation.Name,
            Modell = detail.ModellNavigation.Name,
            Consumption = detail.Consumption,
            Color = detail.Color,
            Year = detail.Year,
            Horsepower = detail.Horsepower
        }
    ).ToList();
}