【问题标题】:Circular reference issue in webapi2webapi2 中的循环引用问题
【发布时间】:2018-05-28 19:44:42
【问题描述】:

场景:

实习生可以学习多种技术

数据库设计

ef 视图

结果

控制器代码:

 private InternEntities db = new InternEntities();

    // GET: api/Interns
    public IQueryable<Intern> GetInterns()
    {
        return db.Interns;
    }

我在这里做错了什么?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api2


    【解决方案1】:

    这是一个预期错误,原因是您的类型像Infinity Mirror 一样相互引用。为了解决这个问题,你有几个选择。

    1- 你可以开发一个ViewModel 然后序列化那个:

    public class InternViewModel{
        public int Id {get; set;}
        public String Name {get; set;}
        public List<String> Tehcnologies {get; set;}
    }
    

    2- 您可以选择在您的操作中返回实体时需要的属性:

    public async Task<List<Technology>> Get() {
        var data = dbContext.Set<Technology>().Select(x=> new Technology{
            Id = x.Id,
            Name = x.Name,
            Intern= new Intern {
                 Id = x.Technology.Id,
                 Name = x.Technology.Name,
                 Technologies = null
            }
        });
        return await data.ToListAsync();
    }
    

    3- 仅加载您需要的内容,即Explicit Loading

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多