实体框架仅插入一条记录

时间:2018-08-22 17:05:22

标签: c# oracle asp.net-mvc-5 entity-framework-6

我通过传递3个参数将记录保存在数据库中,传递了number参数以从一个表到另一个表中选择记录数。但是,写入的循环仅插入1条记录,而不是传递的number参数。

我正在使用Entity Framework中的Take()方法来选择记录。它仅在循环中插入最后一条记录

public async Task<bool> Save(string company, int number, string registrationNumber)
{
    using (var trans = _dbContext.Database.BeginTransaction())
    {
        var db = new SibaCiidDbContext();
        var dbSet = _dbContext.Set<IntermediaryAssignment>();

        // pick number of records 
        var data = await (from s in db.StickerDistributions
                          where s.Dispatched == false &&  
                                s.CompanyCode == company
                          select s).Take(number).ToListAsync();

        var intermediary = (await _repo.FindBy(s => s.RegistrationNumber  == registrationNumber && 
                                                    s.Status == EntityStatus.Active)).FirstOrDefault();

        var entity = new IntermediaryAssignment();

        foreach (var sticker in data)
        {
            entity.CompanyCode = sticker.CompanyCode;
            entity.StickerCode = sticker.StickerCode;
            entity.RegistrationNumber = intermediary.RegistrationNumber;
            entity.Status = EntityStatus.Active;
            entity.CreatedDate = DateTime.Now;
            entity.Dispatched = false;
            entity.IntermediaryType = intermediary.IntermediaryType;

            dbSet.Add(entity);
        }

        trans.Commit();

        return  await _dbContext.SaveChangesAsync() > 0;
    }
}

1 个答案:

答案 0 :(得分:1)

您正在创建一个实体,然后将其更新3次。您需要为每个新记录创建一个新实体。

在循环中移动new IntermediaryAssignment()

     foreach (var sticker in data)
     {
            var entity = new IntermediaryAssignment();


            entity.CompanyCode = sticker.CompanyCode;
            entity.StickerCode = sticker.StickerCode;
            entity.RegistrationNumber = intermediary.RegistrationNumber;
            entity.Status = EntityStatus.Active;
            entity.CreatedDate = DateTime.Now;
            entity.Dispatched = false;
            entity.IntermediaryType = intermediary.IntermediaryType;


            dbSet.Add(entity);

        }