【发布时间】:2018-04-08 19:48:49
【问题描述】:
我在 SQL Server 中有一个现有数据库,因此我创建了一个新的 C# ASP.NET MVC 项目并更新了 web.config 以指向现有数据库(实际上只保存了当前的 AspNetXxxx 表集)。
我创建了一些模型类:
public class Project
{
[Key]
public int Id { get; set; }
public string ProjectName { get; set; }
public string ProjectType { get; set; }
public DateTime created { get; set; }
}
public class Portfolio
{
[Key]
public int Id { get; set; }
public string PortfolioName { get; set; }
public List<Project> Projects { get; set; }
}
public class PortfolioContext : DbContext
{
public DbSet<Project> Projects { get; set; }
public DbSet<Portfolio> Portfolios { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>()
.Property(p => p.Id)
.HasColumnName("ProjId");
modelBuilder.Entity<Portfolio>()
.Property(p => p.Id)
.HasColumnName("PortId");
}
}
然后我使用包管理器控制台:Enable-Migrations(使用我的新 ContextType 或 PortfolioContext)、Add-Migration,然后是 Update-Database。
我还创建了相关的PortfolioController 和相关视图(使用向导中的现有上下文)。
现有数据库尚未使用新表进行更新 - 但是当我运行应用程序时,它工作正常,并且在关闭站点并重新打开后,它仍然具有我创建的投资组合,因此它显然正在存储某处的细节……但它们在哪里?
查看迁移记录,代码如下:
public override void Up()
{
CreateTable(
"dbo.Portfolios",
c => new
{
PortfolioId = c.Int(nullable: false, identity: true),
PortfolioName = c.String(),
})
.PrimaryKey(t => t.PortfolioId);
CreateTable(
"dbo.Projects",
c => new
{
ProjectId = c.Int(nullable: false, identity: true),
ProjectName = c.String(),
ProjectType = c.String(),
created = c.DateTime(nullable: false),
Portfolio_Id = c.Int(),
})
.PrimaryKey(t => t.ProjectId)
.ForeignKey("dbo.Portfolios", t => t.Portfolio_Id)
.Index(t => t.Portfolio_Id);
}
public override void Down()
{
DropForeignKey("dbo.Projects", "Portfolio_Id", "dbo.Portfolios");
DropIndex("dbo.Projects", new[] { "Portfolio_Id" });
DropTable("dbo.Projects");
DropTable("dbo.Portfolios");
}
...看来这些表已经正确设置了所有者“dbo”...我只是不知道在哪里...
【问题讨论】:
-
你能显示 web.config 吗?好像找不到你的数据库,创建了一个本地数据库。
-
转到 PMC 并执行
Get-Migrations -verbose。然后查看以Target database is:开头的输出行
标签: .net sql-server asp.net-mvc entity-framework-6