在我的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
在控制台中运行@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");
}
}
如果数据库中的结果是您想要的,则我假设您至少在错误的其中一个命令上运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句