ASP.NET中DbSet.AddRange方法不存在报错,批量添加记录求助
批量添加记录时DbSet的AddRange方法找不到
我尝试给数据库表批量添加记录,但context.myTbl.AddRange()方法找不到,相关代码和错误信息如下:
相关代码
public void buy(string products) { var producs1 = products.Split(','); List<buyProducs_tbl> records = new List<buyProducs_tbl>(); //var bytes = Convert.FromBase64String(Request.Cookies["userID"].Value); //var output = MachineKey.Unprotect(bytes, "⇆⇍$n=࿓↖BQ⟳$↢T↥↣v↟➝ZS▶#⇀↚@↟➔S♜u❄4♬♨⇆↟3Xw3$⇀♭↩4ncC⇄↱"); //string result = Encoding.UTF8.GetString(output); //var bytes2 = Convert.FromBase64String(Request.Cookies["userPhone"].Value); //var output2 = MachineKey.Unprotect(bytes, "↯)➶N⇩)~↤R↖↕↦↩cD7↤8m❆yA2@⇅VTE↗↡♟Q8↙2F)U$⇆ix)¢➘⇁↢❅3↶"); //string result2 = Encoding.UTF8.GetString(output); foreach (var i in producs1) { Random rand = new Random(); buyProducs_tbl setBuyProducs_tbl = new buyProducs_tbl(); setBuyProducs_tbl.code = rand.Next(10000, 99999).ToString(); setBuyProducs_tbl.personName="sdf"; setBuyProducs_tbl.personPhone = "fd"; setBuyProducs_tbl.products = int.Parse(i); setBuyProducs_tbl.status = false; records.Add(setBuyProducs_tbl); } context.buyProducs_tbl.AddRange(records); context.SaveChanges(); }
错误信息
Error 7 'System.Data.Entity.DbSet<MvcApplication2.Models.buyProducs_tbl>' does not contain a definition for 'AddRange' and no extension method 'AddRange' accepting a first argument of type 'System.Data.Entity.DbSet<MvcApplication2.Models.buyProducs_tbl>' could be found (are you missing a using directive or an assembly reference?) [myProject]\project\MvcApplication2\MvcApplication2\Controllers\HomeController.cs 85 36 MvcApplication2
解决方法
- 检查EF版本:
AddRange是Entity Framework 6及以后版本才支持的方法,若你使用的是EF 5或更早版本,DbSet没有这个方法。请升级EF到6.x及以上版本,或者改用循环逐个添加的方式。 - 确认命名空间:确保代码文件顶部添加了
using System.Data.Entity;,AddRange是该命名空间下的扩展方法,未引用的话编译器无法识别。 - 临时替代方案:如果暂时无法升级EF,将
AddRange替换为循环添加:foreach (var record in records) { context.buyProducs_tbl.Add(record); }
内容的提问来源于stack exchange,提问作者عالي بخي
相关产品推荐
相关产品推荐

