使用SaveChangesAsync插入C#获取列表ID

时间:2018-01-20 04:00:04

标签: c# .net .net-core dbcontext

我使用net core到api控制器和Client使用React。 我想在插入数据库后获取列表机会的详细信息,但我不知道如何获取数据的列表ID?

我的代码插入数据。

   var customers = await db.Customers.Where(c =>
    c.Categories.Any(cate =>
     model.CustomerCategories.Contains(cate.CategoryId)
    )
   ).ToListAsync();

   foreach(var customer in customers) {
    if (String.IsNullOrEmpty(model.Name)) {
     opportunityName = customer.FullName;
    }
    var opportunity = new Opportunity {
     StepId = model.StepId,
      Name = opportunityName,
      Email = customer.Email,
      Phone = customer.Phone,
      CustomerId = customer.Id,
      Status = IdentityStatus.Active,
      ExpectedRevenue = model.ExpectedRevenue,
      Probability = model.Probability,
      Notes = model.Note,
      Deadline = model.Deadline,
      OwnerId = OwnerId,
      Reason = model.Reason,
      Revenue = model.Revenue,
      CompleteDate = model.CompleteDate,
    };
    db.Opportunities.Add(opportunity);

   }
   await db.SaveChangesAsync();

1 个答案:

答案 0 :(得分:1)

跟踪要添加的实体,调用SaveChangesAsync,然后再检查它们。 EF将填充他们的密钥。

这里有一些伪造的代码,应该说明这个想法:

   var customers = await db.Customers.Where(c =>
    c.Categories.Any(cate =>
     model.CustomerCategories.Contains(cate.CategoryId)
    )
   ).ToListAsync();

   var opportunities = new List<Opportunity>(customers.Count);

   foreach(var customer in customers) {
    if (String.IsNullOrEmpty(model.Name)) {
     opportunityName = customer.FullName;
    }
    var opportunity = new Opportunity {
     StepId = model.StepId,
      Name = opportunityName,
      Email = customer.Email,
      Phone = customer.Phone,
      CustomerId = customer.Id,
      Status = IdentityStatus.Active,
      ExpectedRevenue = model.ExpectedRevenue,
      Probability = model.Probability,
      Notes = model.Note,
      Deadline = model.Deadline,
      OwnerId = OwnerId,
      Reason = model.Reason,
      Revenue = model.Revenue,
      CompleteDate = model.CompleteDate,
    };
    opportunities.Add(opportunity);
    //db.Opportunities.Add(opportunity);

   }

   db.Opportunities.AddRange(opportunities);
   await db.SaveChangesAsync();

   //foreach (var opportunity in opportunities)
     // Console.WriteLine(opportunity.YourIdPropertyHere);