在 Code First 中添加新的相关表

Add new related tables in CodeFirst

这是我尝试使用代码优先创建新的 table。我的 objective 是 Name table 与 PhoneNumber table 有关系。它实际上对数据库没有任何作用,所以我一定遗漏了一些重要的东西。

我的项目是默认的ASP MVC app.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace ZeroCloud1.Models
{

//包含在ApplicationDbContext中 // public 虚拟 DbSet 博客 { get;放; } // public 虚拟 DbSet 帖子 { get;放; }

     public partial class Blog
{
    public Blog()
    {
        Posts = new HashSet<Post>();
    }

    public int BlogId { get; set; }

    [StringLength(200)]
    public string Name { get; set; }

    [StringLength(200)]
    public string Url { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public partial class Post
{
    public string PostString { get; set; }

    public int ID { get; set; }
}
}

PM> Add-Migration 'TestClass3' Scaffolding migration 'TestClass3'. The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration TestClass3' again.

PM> Update-Database Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Applying explicit migrations: [201704091548342_TestClass3]. Applying explicit migration: 201704091548342_TestClass3. Running Seed method.

我没认出你[can only have one DbContext when using Code-First]1

所以我使用了默认 ASP MVC 站点附带的 ApplicationDbContext 并且它有效