我有这个方法(使用脚手架程序生成):
// POST: api/Recipients
[HttpPost]
public async Task<IActionResult> PostRecipient([FromBody] Recipient recipient)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Recipients.Add(recipient);
await _context.SaveChangesAsync();
return CreatedAtAction("GetRecipient", new { id = recipient.Id }, recipient);
}
如果我尝试发布一个Recipient
对象并将子对象primaryContact
设置为某个值,则EF会给我一个“错误请求”错误。
所以,目前,我正在从Angular 2项目发布Recipient
对象,在Javascript中将primaryContact
属性设置为null,这样EF就不会尝试保存该子对象。但是,当我执行此操作时,EF不会立即在响应中为我提供子对象(它在第二次get
调用后执行)。
我怎么能:
或者使其成为EF,以便在发布Recipient
后立即在返回的响应中加载primaryContact。
// GET: api/Recipients/5
[HttpGet("{id}")]
public async Task<IActionResult> GetRecipient([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var recipient = await _context.Recipients.Include(rec => rec.PrimaryContact).SingleOrDefaultAsync(m => m.Id == id);
if (recipient == null)
{
return NotFound();
}
return Ok(recipient);
}
以下是Recipient
实体:
[Table("Recipient")]
public class Recipient
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string AddressLine2 { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string WorkPhone { get; set; }
public string HomePhone { get; set; }
[Column(TypeName = "datetime")]
public DateTime DateAdded { get; set; }
public int? PrimaryContactId { get; set; }
[ForeignKey("PrimaryContactId")]
public Contact PrimaryContact { get; set; }
}
答案 0 :(得分:0)
在确切了解CreateAtAction()
方法正在做什么之后,我自己弄明白了。
CreateAtAction()
基本上会创建一个“假的”响应,使用recipient
给出的PostRecipient
对象填充正文(这就是为什么它在post action的响应中显示为null) )。
我所要做的就是在上下文保存更改后立即添加recipient = await _context.Recipients.Include(rec => rec.PrimaryContact).SingleOrDefaultAsync(m => m.Id == recipient.Id);
。
修正:
// POST: api/Recipients
[HttpPost]
public async Task<IActionResult> PostRecipient([FromBody] Recipient recipient)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Recipients.Add(recipient);
await _context.SaveChangesAsync();
recipient = await _context.Recipients.Include(rec => rec.PrimaryContact).SingleOrDefaultAsync(m => m.Id == recipient.Id);
return CreatedAtAction("GetRecipient", new { id = recipient.Id }, recipient);
}