在我的ASP.NET MVC应用程序中,我尝试添加从AspNetUsers
表到我的Recipes
表的一对多关系。
运行迁移后,存在从
之间的关系Recipes
到AspNetUsers
的关系,但没有AspNetUsers
到Recipes
这就是我定义模型的方式:
public class ApplicationUser : IdentityUser
{
public List<Recipe> Recipes { get; set; }
<omitted for brevity>
}
public class Recipe
{
<other properties omitted>
public virtual ApplicationUser User { get; set; }
public string UserId { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Recipe> Recipes { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer<ApplicationDbContext>(null);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
我有:
Update-Database
答案 0 :(得分:2)
@NRKirby,我使用了与上面发布的完全相同的代码,这就是数据库中的样子:
我在Id
模型中添加了Recipe
属性。我不知道你是否在省略的属性中有它。
迁移的代码如下:
public partial class InitalCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Recipes",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
// Some other table definitions...
}
public override void Down()
{
// ...
DropForeignKey("dbo.Recipes", "UserId", "dbo.AspNetUsers");
// ...
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.Recipes", new[] { "UserId" });
// ...
DropTable("dbo.AspNetUsers");
DropTable("dbo.Recipes");
}
}
如果数据库中的结果是你想要的,我认为你至少运行了一个错误的命令。
答案 1 :(得分:1)
您想要关联的任何实体必须是同一模型的一部分。
找到您的上下文类并为您的新类型添加EntitySet。