首先使用实体​​框架代码插入数据

时间:2013-03-31 05:51:16

标签: c# asp.net-mvc-3 orm entity-framework-4.1 entity-framework-5

我正在尝试首先使用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; }


}

CONTEX

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();
}

0 个答案:

没有答案