实体框架“包括”包括儿童的子女

时间:2018-06-15 17:05:43

标签: c# .net entity-framework asp.net-core entity-framework-core

我正在使用Entity Framework Core 2.1开发.NET Core 2.1中的项目。

我正在尝试提取一些数据,序列化并返回它。为避免循环循环,我将延迟加载并将以下行添加到Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<wc2018Context>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("WorldCup2018Database"))
        .UseLazyLoadingProxies(false));

    services.AddMvc(options =>
    {
        options.OutputFormatters.Clear();
        options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        }, ArrayPool<char>.Shared));
    });
}

尽管如此,序列化数据仍然会引发循环异常。

申请非常简单 - 你从世界杯中挑选了8支球队,每支球队都有一支球队。我有一个桌子供团队使用,另一个供用户选择。 “pick”类看起来像这样:

public partial class UserLeaguePick
{
    //Columns
    public int Id { get; set; }
    public int UserleagueId { get; set; }
    public int? Pot1TeamId { get; set; }
    ...
    public int? Pot8TeamId {get; set; }

    //Children
    public Team Pot1Team { get; set; }
    ...
    public Team Pot8Team { get; set; }
    public UserLeague Userleague { get; set; }
}

但是,由于Team类具有以下属性,它会挂起:

public ICollection<UserLeaguePick> UserLeaguePickPot1Team { get; set; }
...
public ICollection<UserLeaguePick> UserLeaguePickPot8Team { get; set; }

UserLeaguePick包含子Team个对象,但Team个对象包含UserLeaguePick个对象。

.Include(i => i.Pot1Team)不应仅包含Team,并忽略其子项,除非我专门.ThenInclude(i => i.UserLeaguePickPot1Team)等?

这是抛出错误的代码:

var userleagues = _context.UserLeaguePick
    .Where(w => w.Userleague.LeagueId == id)
    .Include(i => i.Pot1Team)
    ...
    .Include(i => i.Pot8Team)
    .Include(i => i.Userleague)
    .Include(i => i.Userleague.User)
    .Include(i => i.Userleague.League)
    .ToList();
  

Newtonsoft.Json.JsonSerializationException:'使用'WCP.Data.Models.UserLeaguePick'类型检测到自引用循环。路径'[0] .Pot1Team.UserLeaguePickPot1Team'。'

如何限制.Include让孩子回来的孩子?

0 个答案:

没有答案