EF WebAPI 自引用循环



我在 EF 中遇到了自我引用问题,我正在尝试克服它,但仍允许服务能够执行 GET 传入 {[FromODataUri] int key} 一个键并返回一个 IQuerable Obj 以获取扩展表(如有必要(。 下面是表格的精简版本。 关于如何处理这种情况的任何建议。

public class People
{
 public int PeopleId {get;set;}
 public string PeopleName {get;set;}
 public int? ProductId{get;set;}
 public virtual Product Product{get;set;}
}

产品 ID 是产品中的 PK,但不是必需的。按照约定,它不必使用 PK 数据注释覆盖进行装饰。

public class Product
{
   public Product()
   {
      PeopleCollection = HashSet<People>();
   }
   public int ProductId {get;set;}
   public string ProductName {get;set;}
   public virtual ICollection<People> Peoples{get;set;}
}

在这种情况下,我建议使用 DTO 或使用匿名对象,例如:

public IHttpActionResult Get() {
    var response = db.YourTable.Select(x=>new{
       x.PeopleId,
       x.PeopleName,
       x.ProductId,
       Product= new {
         x.ProductId,
         x.ProductName  
       }
    }).toList();
    return Ok(response);
}

这就是我对匿名对象的做法,如果你想使用 DTO,你只需要映射它们,希望这就是你要找的。

仅对于特定 ID:

public IHttpActionResult Get(int id) {
    var response = db.YourDb.Select(x=>new{
       x.PeopleId,
       x.PeopleName,
       x.ProductId,
       Product= new {
         x.ProductId,
         x.ProductName  
       }
    })Where(x=>x.PeopleId == id).toList();
    return Ok(response);
}

请注意,此方法使用查询字符串参数

一段时间

后我想通了。 如果您从 APIController 继承,则会出现自引用问题,但如果您切换到从 ODataController 继承,一切正常。

所以

 public class MyController : ApiController
    {
     ..... Bunch of code here
    }

public class MyController : ODataController
    {
     ..... Bunch of code here
    }

最新更新