我正在使用asp.net 5和EF 7 VS2015开始一个新项目。
我选择了用户管理的项目模板。 现在我想在dbContext中添加一些类,并使用我的新类创建一个新的模式。
这是我的ApplicationDbContext看起来像:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Candidate> Candidates { get; set; }
public DbSet<Manager> Managers { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<Candidate>().Key(x => x.Id);
builder.Entity<Manager>().Key(x => x.Id);
}
}
我无法将我的数据库重新创建或迁移到包含Candidates
和Managers
表格的版本。
我必须输入哪些命令才能显示数据库?我的朋友谷歌和必应向我指出了各个方向,但我找不到任何有用的东西。
答案 0 :(得分:4)
您需要使用新的import UIKit
import Parse
import AVFoundation
class ListaTableViewController: UITableViewController {
var queryArray: [PFObject] = [PFObject]()
override func viewDidLoad() {
super.viewDidLoad()
var query = PFQuery(className:"Restaurantes")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(objects!.count) Restaurantes.")
if let _objects = objects as? [PFObject] {
self.queryArray = _objects
self.tableView.reloadData()
}
} else {
println("Error: \(error!) \(error!.userInfo!)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return queryArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> ListaTableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ListaTableViewCell
//Insert text in tableview
let restaurante = queryArray[indexPath.row] as! PFObject
cell.textCell.text = restaurante.objectForKey("nome") as! String
//Insert images in tableview
if let userPicture = restaurante.objectForKey("imagem1") as? PFFile {
userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
cell.imageBg.image = UIImage(data:imageData!) }
}
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "cell" {
if let destination = segue.destinationViewController as? MenuPageViewController {
if let blogIndex = tableView.indexPathForSelectedRow()?.row {
}
}
}
}
}
命令,例如:
dnx
并运行迁移:
dnx . ef migration add NameOfMigration
答案 1 :(得分:0)
根据ASP.NET 5和Entity 7 RC1,步骤如下:
project.json
你应该看到这种依赖
"EntityFramework.Commands": "7.0.0-rc1-final"
project.json
中,您将拥有以下ef
命令:
"commands": {
"ef": "EntityFramework.Commands",
"web": "Microsoft.AspNet.Server.Kestrel"
}
打开控制台并运行迁移命令。例如:
D:\Projects\MyProject\src\MyProject.Web.Api>dnx ef migrations add Initial --targetProject MyProject.Data.SqlServer
然后查看ef
将在项目中创建的迁移,并使用以下命令将更改应用于数据库(为项目配置的数据库):
D:\Projects\MyProject\src\MyProject.Web.Api>dnx ef database update
请注意,属性--targetProject
允许您指定DbContext所在的项目以及将创建文件夹迁移的位置。如果您的DbContext在您的主项目中,您可以省略(但我建议有一个类库项目,因为这个命令很方便)
在Startup.cs
中,您通常会获得Entity的配置,包括连接字符串。这是一个基本的例子:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; private set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<KuneDbContext>(options => {
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
});
// Add identity here http://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html
services.AddMvc();
// Add application services
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<KuneDbContext>()
.Database.Migrate();
}
}
catch { }
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//Seed Data if you want to load some test data in the DB
//SeedData.Initialize(app.ApplicationServices);
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}