0

I have the following code:

var game = (from k in db.GamerTBLs
where k.UserName == User.Identity.Name
select k.GamerID).Single();
return View(game);

and this is my controller:

[HttpPost]
public ActionResult Create(GameTBL gametbl)
{
    if (ModelState.IsValid)
    {
        db.GameTBLs.Add(gametbl);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }

    var game = (from k in db.GamerTBLs where k.UserName == User.Identity.Name
        select k.GamerID).Single();

    return View(game);
}

I am trying to populate the Gamer ID to the related table Game which has the the foreign key GamerIDFK.

Can any one please shed some light, if you require more information please let me know

Mike Two
  • 44,935
  • 9
  • 80
  • 96
user1137472
  • 345
  • 2
  • 5
  • 20
  • your question is a little confusing, could you explain what the page is supposed to do?, and you could post your models too... – marcos.borunda Mar 25 '12 at 21:40

1 Answers1

0

From the information you provide I supposed your models are something like this:

GamerTBL:

    public int GamerTBLId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<GameTBL> GameTBLs { get; set; }

GameTBL:

    public int GameTBLId { get; set; }
    public string GameName { get; set; }
    public int GamerIDFK { get; set; }

Your controller should be something like this:

[HttpPost]
public ActionResult Create(GameTBL gametbl)
{
    if (ModelState.IsValid)
    {
        //First you get the gamer, from GamerTBLs
        var gamer = db.GamerTBLs.Where(k => k.UserName == User.Identity.Name).SingleOrDefault();
        //Then you add the game to the games collection from gamers
        gamer.GameTBLs.Add(gametbl);
        db.SaveChanges();  
    }
    return RedirectToAction("Index");
}

Entity Framework abstracts foreign keys concepts, you don't have to worry about id or fk, you just "add" objects to collections of objects.

marcos.borunda
  • 1,486
  • 1
  • 17
  • 34
  • I am getting an error on the create is there any additional support you can provide – user1137472 Mar 26 '12 at 21:42
  • This is the error: Error 1 'MvcApplication1.Controllers.GameController.Create(MvcApplication1.Models.GameTBL)': not all code paths return a value C:\UsersMvcApplication1\MvcApplication1\Controllers\GameController.cs 46 29 MvcApplication1 – user1137472 Mar 26 '12 at 21:44
  • my bad, return RedirectToAction("Index"); should be out of the if statement... My answer is updated now – marcos.borunda Mar 26 '12 at 23:54