与EF在foreach中保存异步

时间:2018-08-24 21:15:22

标签: c# entity-framework async-await

我想通过在Foreach循环中进行迭代来保存对象,并将结果返回给控制器

这是控制器代码:

public async Task<HttpResponseMessage> PostSubmissionFirm(JArray ParamList)
{

    logger.Info(string.Format("----------  PricingController Information //// PostSubmissionFirm"));

    if (ParamList.Count > 0)
    {
        try
        {
            string xxx1 = null;
            string xxxx2 = null;
            string xxxx3 = null;
            string xxxx4 = null;

            Cccier Ci = new Cccier (ParamList);
            List<string> verify = Ci.VerifObject();
            if (verify.Count == 0)
            {


                var Premium =  Ci.calculate();


                HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created };
                return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new JsonContent(new { Premium = Premium, , DateExpire = DtExp.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) })
                };
            }
            else
            {
                HttpError err = new HttpError(message);
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, err);
            }
        }
        catch (Exception e)
        {

        }
    }
}

然后该方法计算出我调用的结果:

public async Task<string> calculate()
{
    int i = 1;
    foreach (var Contextli in qlimit)
    {

        Prem= Prm <= 1500 ? 1500 : Math.Round(Premium, 2);
        double Adnal1 = 100;
        double Adnal2 = Math.Round(Adnal1, 2);

        Submi SubRep = new Submi ();
        SubRep.IdSouSubmi  = 90;
        SubRep.IdPremm= i;
        SubRep.IdLi = Idl;
        SubRep.IdFran = idf;

        db.Submi.Add(SubRep);
        await db.SaveChangesAsync();            
    }

    string JSONString = string.Empty;
    JSONString = JsonConvert.SerializeObject(dt);
    return JSONString;
}

但是在foreach循环的第一次迭代之后,我立即收到一条错误消息:

错误:500内部服务器错误{“消息”:“在连接过程中发生任何错误的交易。倒加其他信息,请咨询例外情况。” }

1 个答案:

答案 0 :(得分:1)

问题是这一行:

var Premium = Ci.calculate();

如果您没有使用var,您会发现Premium不是string而是Task<string>

轻松修复:

var Premium = await Ci.calculate();

注意1:尽管该行中没有任何内容遵循c#约定,但应该类似于

var premium = await Ci.CalculateAsync();

注2:calculate返回一个JSON字符串,而您返回的是JsonContent,因此premium将被序列化两次。 calculate应该返回实际的对象。