我正在尝试首先使用 EF 代码和 ASP.NET MVC 3 保存数据
我的 POCO 课
public class UserAccount {
[Key]
public int Id { get; set; }
public string Name { get; set; }
[Required(ErrorMessage="Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
public string Department { get; set; }
public string Category_ID { get; set; }
}
上下文
public class OnlineTest : System.Data.Entity.DbContext {
public DbSet<UserAccount> UserAccounts { get; set; }
public OnlineTest()
: base("OnlineTest")
{
}
}
public class OnlineTestInitializer : DropCreateDatabaseIfModelChanges<OnlineTest> {
protected override void Seed(OnlineTest context)
{
context.UserAccounts.Add(new UserAccount { Name = "Admin", Username = "admin", Password = "adminpass", Department="All", Category_ID = "1" });
base.Seed(context);
context.SaveChanges();
}
}
我的申请开始
protected void Application_Start() {
Database.SetInitializer(new OnlineTestMVC.Models.OnlineTestInitializer());
var contex = new OnlineTest();
contex.Database.Initialize(true);
AreaRegistration.RegisterAllAreas();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
我可以使用默认的种子数据初始化数据库。我的问题是,我无法使用下面的代码插入数据。
var User = new UserAccount { Name = "abc", Username = "abc123", Password = "passwrd", Department = "CS", Category_ID = "2" };
using (var db = new OnlineTest())
{
db.UserAccounts.Add(User);
db.SaveChanges();
}