首页 > 解决方案 > 子资源在完全发展的关系 EF Core 中再次显示

问题描述

我在大学和专业之间的 EF Core 中已经完全建立了一对多的关系。

我需要展示大学 A 及其专业,但这些专业有对大学 A 的引用,并且 A 每次都显示为“JSON 孩子”,我不希望它显示。

有什么办法可以解决这个问题吗?如果有人需要更多继承人的回购:https ://github.com/nambonumestinvisibili/SGrade/tree/master/SGrade

主要的

public class Major : IGradable
    {
        public University University { get; set; }
        public int UniversityId {get;set;}
        public ICollection<Subject> Subjects { get; set; }
        public ICollection<Teacher> Teachers { get; set; }
        public ICollection<ApplicationUser> Users { get; set; }

    }

主要 DTO:(使用 automapper 进行映射)

public class MajorDTO : Major
    {
        public string Type { get; set; } = "Major";
    }

大学

public class University : IGradable
    {
        public ICollection<Major> Majors { get; set; }

    }

统一回购

public class UniversityRepo : GradableRepo<University>, IUniversityRepo
    {
        public UniversityRepo(SGradeContext sgcontext) : base(sgcontext)
        {

        }

        public async Task<University> GetPresentingUniversity(int id)
        {
            IQueryable<University> query = _context.Universities
                //.Include(x => x.Reviews)
                //.Include(x => x.Subjects.Take(5))
                //.Include(x => x.Teachers.Take(5))
                .Include(x => x.Majors);

            return await query.Where(x => x.Id == id).FirstOrDefaultAsync();
        }
    }

控制器的一部分:

// GET: api/Universities/5
        [HttpGet("{id}")]
        public async Task<ActionResult<University>> GetUniversity(int id)
        {
            var university = await _repo.GetPresentingUniversity(id);

            if (university == null)
            {
                return NotFound();
            }

            return _mapper.Map<University, UniversityDTO>(university);
        }

回复:

{
    "type": "University",          //this is university A
    "majors": [
        {
            "university": {        //and here it is repeated
                "majors": [],
                "name": "Uniwersytet Wrocławski",
                "starsRating": 2.5,
                "reviews": null,
                "isConfirmed": true,
                "votes": 0,
                "id": 3
            },
            "universityId": 3,
            "subjects": null,
            "teachers": null,
            "users": null,
            "name": "Informatyka",
            "starsRating": 2.5,
            "reviews": null,
            "isConfirmed": true,
            "votes": 0,
            "id": 1
        }
    ],
    "name": "Uniwersytet Wrocławski",
    "starsRating": 2.5,
    "reviews": [],
    "isConfirmed": true,
    "votes": 0,
    "id": 3
}

标签: c#entity-frameworkasp.net-core

解决方案


在序列化一对多关系时我遇到了类似的问题,这起到了作用:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
                options.JsonSerializerOptions.MaxDepth = 0;
            });
     }

Check if it works for you. Here is a demo project with all types of relationships in EF Core 5, where I had this problem. https://github.com/mikuam/PrimeHotel/commit/ef47a9faeb8111e363adb921287ac9392cd50e97

However, I must admit that exposing Model classed in controllers is not ideal and having Dtos, where you expose only what you should is way better. What's more, you can control how deep you resolve relationships.


推荐阅读