如何检查现有记录

本文关键字:记录 检查 何检查 | 更新日期: 2023-09-27 18:31:18

嗨,人们是 MVC3 的新手和学习,我想知道是否可以允许用户在我的网站上添加游戏时检查游戏是否已全部准备就绪。我想要这个功能,这样我网站上的任何游戏玩家都无法对同一游戏进行整体评论。这样做的原因我有一个页面,用户可以在其中谈论游戏。这就是为什么我想要一种方法在添加新游戏时检查数据库,如果游戏存在。

我的控制器如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using PagedList;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Test.Models;
namespace Test.Controllers
{ 
    public class GameController : Controller
    {
        private gamezoneDBEntities db = new gamezoneDBEntities();
        //
        // GET: /Game/

        public ViewResult Index(string Ordering, string WordFilter, string DisplaySearchResults, int? CounterForPage)
        {
            {
                var Info = db.tblGames.Include(x => x.tblConsole);
            }
            var Games = from b in db.tblGames
            .Where(U => U.UserName == User.Identity.Name)
                        select b;

            switch (Ordering)
            {
                case "HeadlineName":
                    Games = Games.OrderBy(b => b.GameName);
                    break;
                case "DatePosted":
                    Games = Games.OrderBy(b => b.ReleaseYear);
                    break;
                case "DiscriptionDate":
                    Games = Games.OrderBy(b => b.ReleaseYear);
                    break;
                default:
                    Games = Games.OrderByDescending(b => b.ReleaseYear);
                    break;
            }
            int pageSize = 3;
            int pageNumber = (CounterForPage ?? 1);
            var PageNumberResults = Games.ToPagedList(pageNumber, pageSize);
            ViewBag.PageNumberResults = Games.Count();
            if (PageNumberResults.Any())
            {
                return View(PageNumberResults);
            }
            return View("Error");
        }

        [HttpPost]
        public ActionResult Create(tblGame tblgame,
           HttpPostedFileBase image1,
           HttpPostedFileBase image2)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (image1 != null)
                    {
                        string image = image1.FileName;
                        tblgame.Image = image;
                        var image1Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), image);
                        image1.SaveAs(image1Path);
                    }
                    if (image2 != null)
                    {
                        string Image2 = image2.FileName;
                        tblgame.Image2 = Image2;
                        var image2Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), Image2);
                        image2.SaveAs(image2Path);
                    }
                    db.tblGames.Add(tblgame);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.ConsoleNameIDFK = new SelectList(db.tblConsoles, "ConsoleName", "ConsoleName", tblgame.ConsoleNameIDFK);
                return View(tblgame);
            }
            catch
            {
                return View("Upload_Image_Failed");
            }
        }
        //
        // GET: /Game/Create
        public ActionResult Create()
        {
            ViewBag.ConsoleNameIDFK = new SelectList(db.tblConsoles, "ConsoleName", "ConsoleName");
            return View(new tblGame { UserName = @User.Identity.Name });
        } 

        public ViewResult Details(int id)
        {
            tblGame tblgame = db.tblGames.Find(id);
            return View(tblgame);
        }

        //
        // GET: /Game/Edit/5
        public ActionResult Edit(int id)
        { 
                tblGame tblgame = db.tblGames.Single(i => i.GameID == id);
                ViewBag.ConsoleNameIDFK = tblgame.ConsoleNameIDFK;
                return View(tblgame);
            }

        [HttpPost]
        public ActionResult Edit(tblGame tblgame, HttpPostedFileBase Image, int id,
            HttpPostedFileBase image2)
        {
            if (ModelState.IsValid)
            {

                if (Image != null)
                {
                    string image = Image.FileName;
                    tblgame.Image = image;
                    var image1Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), image);
                    Image.SaveAs(image1Path);
                }
                if (image2 != null)
                {
                    string Image2 = image2.FileName;
                    tblgame.Image2 = Image2;
                    var image2Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), Image2);
                    image2.SaveAs(image2Path);
                }
                db.tblGames.Attach(tblgame);
                db.Entry(tblgame).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Edit");
            }
            ViewBag.ConsoleNameIDFK = new SelectList(db.tblConsoles, "ConsoleName", "ConsoleName", tblgame.ConsoleNameIDFK);
            return View(tblgame);
        }

        //
        // GET: /Game/Delete/5
        public ActionResult Delete(int id)
        {
            tblGame tblgame = db.tblGames.Find(id);
            return View(tblgame);
        }
        //
        // POST: /Game/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                tblGame tblgame = db.tblGames.Find(id);
                db.tblGames.Remove(tblgame);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View("Error");
            }
        }  

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

我很难尝试查看游戏 allreday 是否存在,因为我有使用户独特的代码。我需要这段代码,否则我可能会有一个语句来检查所有游戏的数据库,如果游戏存在我添加的这段代码,这对我来说有点困难,这就是我来到这里的原因。

我已将以下内容添加到我的控制器中:

[HttpPost]
public ActionResult Create(tblGame tblgame, HttpPostedFileBase image1, HttpPostedFileBase image2)
{
    try
    {
        if (ModelState.IsValid)
        {
            var mygame = db.tblGames.Where(x => x.GameName == tblgame.GameName).SingleOrDefault();
            if (mygame != null)
            {
                if (image1 != null)
                                {
                                    string image = image1.FileName;
                                    tblgame.Image = image;
                                    var image1Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), image);
                                    image1.SaveAs(image1Path);
                                }
                                if (image2 != null)
                                {
                                    string Image2 = image2.FileName;
                                    tblgame.Image2 = Image2;
                                    var image2Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), Image2);
                                    image2.SaveAs(image2Path);
                                }
                                db.tblGames.Add(tblgame);
                                db.SaveChanges();
                                return RedirectToAction("Index");
            }
            else
            {
                //otherwise we add a generic error to the model state
                ModelState.AddModelError("", "A game review already exists");
            }
        }
    }
    catch
    {
        return View("Upload_Image_Failed");
    }
    //if arrive here the model is returned back to the view with the errors added
    return View(tblgame);
}

如何检查现有记录

在保存之前,可以使用 Linq 查询检查游戏是否存在。假设在我的示例中,字段名称足以识别游戏评论,您可以这样做

    [HttpPost]
    public ActionResult Create(tblGame tblgame, HttpPostedFileBase image1, HttpPostedFileBase image2)
    {
        try
        {
            if (ModelState.IsValid)
            {
              var mygame = db.tblGames.Where(x => x.GameName == tblgame.GameName).SingleOrDefault();
              if (mygame != null)
              {
                if (image1 != null)
                {
                  string image = image1.FileName;
                  tblgame.Image = image;
                  var image1Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), image);
                  image1.SaveAs(image1Path);
                }
                if (image2 != null)
                {
                  string Image2 = image2.FileName;
                  tblgame.Image2 = Image2;
                  var image2Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), Image2);
                  image2.SaveAs(image2Path);
                }
                db.tblGames.Add(tblgame);
                db.SaveChanges();
                //All ok, we redirect to index or to Edit method. (PRG pattern)
                return RedirectToAction("Index");
              }
              else
              {
                //otherwise we add a generic error to the model state
                ModelState.AddModelError("", "A game review already exists");
              }
            }
        }
        catch
        {
          //return View("Upload_Image_Failed");
          ModelState.AddModelError("", "The upload of the images as failed");
        }
        //if we arrive here, the model is returned back to the view with the errors added
        ViewBag.ConsoleNameIDFK = new SelectList(db.tblConsoles, "ConsoleName", "ConsoleName", tblgame.ConsoleNameIDFK);
        return View(tblgame);
    }

根据您提供的代码,您应该更改Create操作方法:

[HttpPost]
public ActionResult Create(tblGame tblgame, // tblGame is the new game being created
       HttpPostedFileBase image1,
       HttpPostedFileBase image2)
{
    try
    {
        if (ModelState.IsValid)
        {
             /* Go to DB and check if there's a Game already there that matches this
                one just being added. What's the property you want to check against?
                That's something you must provide. I just wrote GameName to show you
                how to do this... */
             var game = db.tblGames.Single(g => g.GameName == tblGame.GameName);
             /* OK, can proceed adding this game... since there's no game in the DB
                that matches this one being added. */
             if (game == null)
             {
                // Continue saving the new game
             }
             else /* Abort and display a message to user informing that there's a game
                  already. */
             {
                // TODO
             }
        }
    }
}

我很难看到游戏是否全部存在 我有使用户独特的代码。我需要这段代码,否则我 本可以有一个检查数据库所有游戏的语句,并且 如果游戏存在此代码,则抛出错误,我已添加它是一个 对我来说有点难,这就是我来到这里的原因。

由于每个用户都有自己独特的游戏列表,因此您将有一个名为GameMapping的表,它将每个用户映射到游戏。

身份证 |用户标识 |游戏编号

ID 是自动递增的主键。UserID 是链接到用户主 ID 的外键,而 GameID 是链接到特定游戏的外键。

var user = GetUser(); // not sure what you use to identity users, but that logic would go here
var game = Db.Games.Where(g => g.Name == tblGame.Name).First();
Db.GameMapping
   .Where(g => g.UserID == user.ID) // filter out all records for that user
   .Select(g => g.GameID) // select just the game IDs
   .Contains(game.ID) // see if the game id they want to add is in that list

下面是执行相同检查的替代 LINQ 查询。

if (Db.GameMapping.Where(gm => gm.UserID == User.ID && gm.GameID == game.ID).Count() > 0)
     // user already has that game
else
     // they do not 

看起来你的项目的增长开始引入错误并变得有点压倒性。在项目中实现此游戏检查代码之前,我强烈建议先设置一个小单元测试。创建一个独立于大项目的新项目,添加数据库库并创建一个非常小的测试,您可以在其中输入游戏和用户,并查看此代码是否按预期工作。一旦你知道你的实施是可靠的,那就把它集成到更大的项目中。

当您将项目分解为更小的部分并测试每个部分时,您可以大大降低调试整个项目的复杂性。祝你好运。