简体   繁体   English

插入多个数据ASP.NET MVC时出现问题

[英]Problem when inserting multiple data ASP.NET MVC

I am having trouble when inserting multiple records. 插入多个记录时遇到麻烦。 When I try to insert 2 records the debugger shows the count of 2 but it only saves 1 record. 当我尝试插入2条记录时,调试器显示的计数为2,但仅保存1条记录。

This is my code in my manager class 这是我经理班上的代码

public void Create(IEnumerable<CollectionModel> p )
{
    collection module = new collection();
    foreach (var asa in p)
    {               
        module.AccountId = 1;
        module.Amount = asa.Amount;
        module.NameSou = asa.NameSou;
        module.Date = asa.Date;
        module.CreatedDatetime = DateTime.Now;
        module.UpdatedDatetime = DateTime.Now;

        _context.collection.Add(module);
    }
    _context.SaveChanges();
}

Entity Framework offers two methods to insert records into database. 实体框架提供了两种将记录插入数据库的方法。 Add() method allows to insert a single entity. Add()方法允许插入单个实体。 AddRange() method inserts an IEnumerable collection. AddRange()方法插入IEnumerable集合。 You can find more information from here . 您可以从此处找到更多信息。

Example: 例:

 public void Create(IEnumerable<CollectionModel> args )
 {
    var modules = args.Select(asa=> new collection{
       AccountId = 1,
       Amount = asa.Amount,
       NameSou = asa.NameSou,
       Date = asa.Date,
       CreatedDatetime = DateTime.Now,
       UpdatedDatetime = DateTime.Now
      }).ToList(); 
    _context.collection.AddRange(modules);
   _context.SaveChanges();
}

Small Correction in your code. 代码中的小更正。 You are creating one module and updating the same every time. 您正在创建一个模块,并每次都对其进行更新。 So it will always save the list of last item in your case list of last item of p. 因此,它将始终将最后一项的列表保存在p的最后一项的案例列表中。

 public void Create(IEnumerable<CollectionModel> p )
 {
   foreach (var asa in p)
     {   
       collection module = new collection();            
       module.AccountId = 1;
       module.Amount = asa.Amount;
       module.NameSou = asa.NameSou;
       module.Date = asa.Date;
       module.CreatedDatetime = DateTime.Now;
       module.UpdatedDatetime = DateTime.Now;

      _context.collection.Add(module);
    }
   _context.SaveChanges();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM