Replace the code with:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Data.Entity.Infrastructure;namespace TeamWebSite.Data
{
public classTeamWebSite : DbContext
{
//EF Container
public DbSet<Player> players
{
get;
set;
}
}
//Standard old POCO class
public class Player
{
public Player() { }
public int PlayerID { get; set; }
public string PlayerName { get; set; }
public string PlayerDescription { get;set; }
public int PlayerAge { get; set; }
//Standard Select
publicList<Player> GetAllPlayers()
{
TeamWebSite db =new TeamWebSite();
return db.players.ToList<Player>();
}
//Insert
publicvoid CreatePlayer(string PlayerName, string PlayerDescription,int PlayerAge)
{
TeamWebSite db =new TeamWebSite();
db.players.Add(newPlayer { PlayerName = PlayerName, PlayerDescription = PlayerDescription, PlayerAge = PlayerAge });
db.SaveChanges();
}
//Edit
publicvoid EditPlayer(int PlayerID, string PlayerName,string PlayerDescription,int PlayerAge)
{
TeamWebSite db =new TeamWebSite();
Player p = db.players.SingleOrDefault(player => player.PlayerID == PlayerID);
if (p !=null)
{
p.PlayerName = PlayerName;
p.PlayerAge = PlayerAge;
p.PlayerID = PlayerID;
db.SaveChanges();
}
else
{
thrownew ApplicationException("Can not find the player");
}
}
//Delete
publicvoid DeletePlayer(int PlayerID)
{
TeamWebSite db =new TeamWebSite();
Player p = db.players.SingleOrDefault(player => player.PlayerID == PlayerID);
if (p !=null)
{
db.players.Remove(p);
db.SaveChanges();
}
else
{
thrownew ApplicationException("Can not find the player");
}
}
}
//Called by Global.asax to reload the database in a situation when the model changes from
//the physical DB
public class WebSiteInitializer : RecreateDatabaseIfModelChanges<TeamWebSite>
{
protected override void Seed(TeamWebSite context)
{
var Players =new List<Player>
{
newPlayer { PlayerID= 1, PlayerName="John", PlayerAge=31, PlayerDescription="older player" },
newPlayer { PlayerID=2, PlayerName="sTEVE" , PlayerAge=23, PlayerDescription="asdasd" }
};
Players.ForEach(d => context.players.Add(d));
}
}
}
OK so it might look like a lot but break it down and it's not very complicated at all. There are 3 classes (Yes we should have them in separate files but to keep things all in one page for brevity I am being very very bad). The three classes:
TeamWebSite - inherits from DBContext (part of the EF framework), publishes our main property: public DbSet<Player> players.
Person - standard basic old POCO class. Nothing really special.
WebSiteInitializer - class that we hook to from global.asax to make sure we keep the EF datamodel synced with the database.