所以我运行了 SQLServerExpress 2008 R2 和 Visual Studio 2010。我相信我有一个 SQL Server 实例正在运行(图 1)。我被告知,如果我没有在我的程序中指定连接字符串,EF 将在本地 SQL Server 实例上创建数据库。它不是。. .我收到错误
我的代码如下:
在global.asax.cx
:
protected void Application_Start()
{
Database.SetInitializer(new DatabaseInit());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Horse.cs
:
public class Horse
{
public int HorseID { get; set; }
public string Name { get; set; }
public virtual Participant Participant { get; set; }
}
Participant.cs
:
public class Participant
{
public int ParticipantID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
public Horse Horse { get; set; }
}
MelbourneCupDbContext
:
public class MelbourneCupDbContext : DbContext
{
public DbSet<Horse> Horses;
public DbSet<Participant> Participants;
}
DatabaseInit
:
public class DatabaseInit : DropCreateDatabaseAlways<MelbourneCupDbContext>
{
protected override void Seed(MelbourneCupDbContext context)
{
var Horses = new List<Horse>
{
new Horse{Name="Americain"},
new Horse{Name="Jukebox Jury"},
new Horse{Name="Dunaden"}
....
};
foreach (Horse h in Horses)
context.Horses.Add(h);
context.SaveChanges();
}
}
最后,当我尝试使用数据库 ( SignUpController.cs
) 时:
private MelbourneCupDbContext dbContext = new MelbourneCupDbContext();
[HttpGet]
public ActionResult Index()
{
IEnumerable<Horse> allHorsesList = dbContext.Horses.ToList();
return View(allHorsesList);
}
当我尝试调用源不能为空的 ToList 时出现错误。
哈尔普
图。1