1

我在网站上有横幅。当横幅显示时,我在数据库中增加字段。这是代码:

public Banner GetBanner(CategoryBanner type)
        {
            var banners = Database.Banners.Where(b => b.IsPublish.Value &&
                                                      b.Category.Value == (int)type &&
                                                      b.PeriodShowCountAlready < b.PeriodShowCount || b.IsPublish.Value && b.Category.Value == (int)type &&
                                                      b.ShowNext < DateTime.Now);

            var count = banners.Count();
            if (count != 0)
            {
                var skip = new Random().Next(banners.Count() - 1);

                Banner banner = banners.Skip(skip).FirstOrDefault();

                if (banner != null)
                {
                    UpdatePeriodShowCountAlready(banner); // problem is inside this method

                    if (banner.ShowStart == null)
                        UpdateShowStartAndEnd(banner); 

                    return banner;
                }
            }
            return null;
        }

private void UpdatePeriodShowCountAlready(Banner banner)
        {
            try
            {
                if (banner != null)
                {
                    banner.PeriodShowCountAlready++;

                    if (banner.PeriodShowCountAlready >= banner.PeriodShowCount && banner.ShowNext < DateTime.Now)
                    {
                        banner.PeriodShowCountAlready = 0;
                        banner.ShowStart = null;
                        banner.ShowNext = null;
                    }

                    Database.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }

        }

而且,我收到以下错误:

System.Data.Linq.ChangeConflictException
Row not found or changed.

这个错误很容易重现:按住F5几秒钟就够了。我明白为什么会发生这个错误,但是如何正确地重写我的代码呢?
谢谢。

4

0 回答 0