同时添加两个对象相互依赖

时间:2017-05-31 08:52:57

标签: linq

我是linq的新手。 我正在用net core构建一个web api项目。 这就是我想要处理的: 我有两张桌子:“1”作为文件,“2”作为caisse。

在同一个查询中,我想添加表1和表2。 问题是我不知道表2的id .id是自动增量。 我有想法获得Max id,但我认为这是一个不合适的解决方案。 我该如何解决这个问题?

[HttpPost("addDocument")]
  public IActionResult AddShoppingCart([FromBody]DocumentDto document)
{
if (Document== null)
            {
                return BadRequest();
            }
            try
            {
                Caisse caisse = new Caisse();
                 caisse.dateDocumentRelease=Date.now();
                 caisse.dateOfAmount=Date.now();
                _iCaisseService.AddCaisse(caisse)
              // here i don't konw the id of the caisse after adding it 
               _iDocumentService.AddDocument(document);

                if (!_iDocumentService.Save())
                {
                    return StatusCode(500, "A problem happened while handling your request.");
                }
                return StatusCode(200, "good");            }
            catch (Exception ex)
            {
                return StatusCode(500, "A problem happened while handling your request.");
            }
}

1 个答案:

答案 0 :(得分:0)

public Document AddCaisse(Caisse caisse)
        {
            return _context.Caisse .Add(caisse).Entity;
        }

这个linq查询解决了这个问题。 在post方法中,我调用addCaisse。

var object= _iDocumentService.addCaisse(caisse);
return Ok(object.Id);