因此,首先我不知道我使用的實體框架版本是什麼。我假設它是4,但我該如何檢查?實體框架不會在數據庫中創建表格
其次,我有以下連接字符串在web.config中:
<connectionStrings>
<add name="DBEntites"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
正如你可以看到他們是相同的DB。實際上它們是由asp.net成員提供商創建的數據庫。
現在我有以下型號:
public class Profile {
[Key]
public string username { get; set; }
[Display(Name = "Full Name")]
public string FullName { get; set; }
}
是不是很簡單?
然後我有下面的類連接到數據庫:
public class DBEntities : DbContext {
public DbSet<Profile> Profiles { get; set; }
}
然後在我的賬戶控制器,事實上這是當你選擇一個新的MVC3項目由VS2010創建相同的控制器。
[HttpPost]
public ActionResult Register(RegisterModel model) {
if (ModelState.IsValid) {
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
Profile pm = new Profile();
pm.username=model.UserName;
pm.FullName="unknown";
db.Profiles.Add(pm);
db.SaveChanges();
if (createStatus == MembershipCreateStatus.Success) {
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
} else {
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
所以當我運行這個應用程序,它沒有例外運行。如果我添加一個新用戶,新用戶將被添加到asp.net成員資格表中。所以根據我的理解,Entity框架應該創建一個名爲「Profile」的表,其中包含兩列「username」和「fullname」。
但是,它不是。爲什麼代碼可以毫無例外地穿過,db.SaveChanges()
可以通過,但是沒有創建表?
我在做什麼錯?
編輯:我認爲如果我嘗試創建一個具有相同用戶名的條目(顯然不能,因爲它是一個主鍵),那麼會引發異常,說該條目已經存在。
但我似乎找不到表!
如何創建一個單獨的數據庫? – masfenix 2011-05-06 19:12:05
如果您希望EF爲您生成數據庫和表格,則不會創建任何數據庫。 – 2011-05-06 19:36:36