2012-04-14 6 views
2

こんにちは、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のexsits場合、私は、ユーザーがユニークなコードを持っていると見しようとしてextermly苦労がありました。私はこのコードが必要です。そうでなければ、すべてのゲームのデータベースをチェックし、このコードが存在しないゲームであればエラーをスローすることができます。

私は私のコントローラに以下を追加しました:

[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); 
} 
+0

ページに表示されるように、編集を承認するには十分な評判を持つ人がさらに必要です。 –

答えて

1

あなたが提供したコードから、あなたは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 
      } 
     } 
    } 
} 
+0

私はこのコードを追加して、お返事ありがとうございます。 – user1137472

+0

私が書いたコード私の編集した質問 – user1137472

+0

あなたのコードにエラーがあります...それは問題ですか? –

3

あなたがいるかどうかを確認するために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); 
    } 
+0

私の編集した質問に書いたコードをコンパイルするには – user1137472

+0

次のエラーを表示していた(x => x.name = tblgame.Name)コードを試しました:私のデータベースにある "GameName"に変更しましたが、それでもエラーがスローされます:暗黙のうちに 'string'の型を 'bool'に変換することはできません – user1137472

+0

私の過ちを解消します。それは等しい条件なので、 '=='にする必要があります。 – Iridio

0

I have had extermly hard time trying to see if game allreday exsits as i have code that makes users unique. I need this code otherwise I could have had a statment that checks the database for all games and throw an error if a game exsisted with this code i have added its a bit hard for me that is why i have come here.

のように行うことができますゲームのレビューを識別するのに十分です、あなたはこのような何かをGameMappingと呼ばれるテーブルを持っているでしょう各ユーザーをゲームにマップします。

ID |ユーザーID | GameID

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 

プロジェクトの成長は、エラーを導入し、ビット圧倒的になり始めているように見えます。あなたのプロジェクトでこのゲームのチェックコードを実装する前に私が強くお勧めするのは、小さなユニットテストを最初にセットアップすることです。大きなプロジェクトとは別に新しいプロジェクトを作成し、データベースライブラリを追加し、ゲームやユーザーに入力する非常に小さなテストを作成し、期待どおりに動作するかどうかを確認します。実装が堅実であることがわかったら、それをより大きなプロジェクトに統合します。

プロジェクトをより小さな部分に分割し、各部分をテストすると、全体をデバッグする複雑さが大幅に軽減されます。がんばろう。

関連する問題