简体   繁体   English

使用WebAPI和实体框架通过JSON发送和接收不同的模型

[英]Sending and receiving different models over json with webapi and entity framework

I'm very new to entity framework and web api so please excuse me if what I'm trying to do doesn't make much sense! 我对实体框架和Web API还是很陌生,所以如果我想做的事情没有什么意义,请原谅! Is it possible to send one model on a post and receive a different model on a get? 是否可以在帖子中发送一个模型并在获取时接收另一个模型? My example. 我的例子。

I have a very simple companies model: 我有一个非常简单的公司模型:

  public class Company
    {
        [Required]
        public string companyName { get; set; }
        public virtual List<Branch> branches { get; set; }
    }

 public class Branch
    {
        public int companyID { get; set; }
        public string branchName { get; set; }
        public string address { get; set; }
        public string postcode { get; set;}
        public string phoneNumber { get; set; }
        public virtual Company company { get; set; }
    }

When I post to myapp/api/companies I want to be able to include a list of branches to add alongside the company, this is currently working perfectly however, my front end designer has requested that the companies come back without the branches attached. 当我发布到myapp / api / companies时,我希望能够包括要在公司旁边添加的分支机构列表,该列表目前运行良好,但是,我的前端设计师要求这些公司在没有分支机构的情况下回来。 I have tried [jsonIgnore] against the branches and this works for the GET but it also stops the branches from writing on a post. 我已经对分支尝试过[jsonIgnore],这对GET有用,但它也阻止了分支在帖子上写东西。 Is there some way to apply the jsonIgnore on the controller perhaps? 有没有办法在控制器上应用jsonIgnore?

Should I try and convince my front-end guy to just ignore the branch data or is there some way I could omit it in the response? 我应该说服我的前端人员忽略分支数据,还是可以通过某种方式在响应中忽略它?

Thanks 谢谢

Chris 克里斯

The way I finally managed to do this was to use eager loading instead of lazy loading. 我最终设法做到这一点的方法是使用紧急加载而不是延迟加载。 To achieve that remove virtual from each of the relations. 为了实现这一点,从每个关系中删除虚拟关系。 This stops EF from getting the relations automatically then in any code that returns the object use .Include() to include any relations you want back in that return. 这将阻止EF自动获取关系,然后在返回对象的任何代码中使用.include()将EF包含在该返回中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM