【问题标题】:Get Parent based on string value and all its children with Entity Framework Core [duplicate]使用 Entity Framework Core 根据字符串值及其所有子项获取父项 [重复]
【发布时间】:2019-06-13 13:28:44
【问题描述】:

我目前正在获取一个基于这样的字符串属性的对象:

return DbContext.Products.FirstOrDefault(p => p.Route == route);

这工作正常,但我现在需要像这样获取模型中相关的子对象(好处):

public IList<Benefit> Benefits { get; set; }

我如何才能获得此产品及其所有儿童福利?

类似这样的东西,但这不起作用:

return DbContext.Products.Include("Benefits")FirstOrDefault(p => p.Route == route);

谢谢

【问题讨论】:

  • 定义“不起作用”
  • 顺便说一句,希望你错过了“。”在 ("Benefits") 和 FirstOrDefault() -> .Include("Benefits").FirstOrDefault 之间。希望这是写 OP 时的错字?

标签: linq entity-framework-core


【解决方案1】:

你可以尝试如下:

return DbContext.Products.Include(x=>x.Benefits).FirstOrDefault(p => p.Route == route);

在启动类中:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2011-01-22
    • 2019-01-28
    相关资源
    最近更新 更多