如何让EF在发布后保存孩子或加载儿童(保存)?

时间:2017-10-31 15:37:28

标签: c# entity-framework entity-framework-6

我有这个方法(使用脚手架程序生成):

    // 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调用后执行)。

我怎么能:

  1. 避免将Javascript属性设置为null,以便EF不会尝试保存它
  2. 或者使其成为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);
    }
    
  3. 以下是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; }
    }
    

1 个答案:

答案 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);
    }