处理DataContext和代码分析消息

时间:2011-07-14 10:30:32

标签: c# .net asp.net

我刚刚对其中一个项目进行了代码分析,当我收到以下警告信息时有点意外;

CA2000:Microsoft.Reliability:在方法'DataImport.ImportSalesExecBackFill(Stream)'中,在对所有引用超出范围之前,在对象'dc'上调用System.IDisposable.Dispose。

参考以下代码;

            using (DataDataContext dc = new DataDataContext(ConfigurationManager.ConnectionStrings["data"].ConnectionString))
            {
                List<tableSale> sample = (from s in dc.tableSales
                                                   where bfData.Select(d => d.RegNo).ToList().Contains(s.RegNum)
                                                   select s).ToList();

                var matches = (from s in sample
                               join bfd in bfData on s.RegNum equals bfd.RegNo
                               where string.IsNullOrEmpty(s.OpDesc)
                               select new { UserId = s.UserID, OpId = String.Format("SMMT{0}-{1}", s.DlrNo, bfd.OpName), OpDesc = bfd.OpName }).ToList();

                List<tableSale> updQuery = (from s in dc.tableSales
                                                     where matches.Select(d => d.UserId).ToList().Contains(s.UserID)
                                                     select s).ToList();

                foreach (tableSale rec in updQuery)
                {
                    rec.OpID = matches.Where(s => s.UserId == rec.UserID).Select(s => s.OpId).First();
                    rec.OpDesc = matches.Where(s => s.UserId == rec.UserID).Select(s => s.OpDesc).First();
                }

                dc.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);

                using (PCSalesDataContext pcdc = new PCSalesDataContext(ConfigurationManager.ConnectionStrings["LatData"].ConnectionString))
                {
                    List<tblSale> upd700 = (from s in pcdc.tblSales
                                            where matches.Select(d => d.UserId).ToList().Contains(s.UserID)
                                            select s).ToList();

                    foreach (tblSale rec in upd700)
                    {
                        rec.OpID = matches.Where(s => s.UserId == rec.UserID).Select(s => s.OpId).First();
                        rec.OpDesc = matches.Where(s => s.UserId == rec.UserID).Select(s => s.OpDesc).First();
                    }

                    pcdc.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);
                }

                result = true;
            }   

现在我的印象是datacontext将始终放在using语句范围的末尾。我错过了什么,或者这是一条我可以高兴地忽略的警告信息?

1 个答案:

答案 0 :(得分:3)

using语句中可能有太多函数调用(超过63个)。 参见

http://connect.microsoft.com/VisualStudio/feedback/details/557088/vb-net-using-block-ca2000-warning-if-too-many-calls

https://connect.microsoft.com/VisualStudio/feedback/details/607263/warning-ca2000-although-object-is-disposed

所以,是的,这是代码分析中的一个错误,您可以忽略该消息,但无论如何您可能想要重构代码。