【问题标题】:Error on running migration in MVC Core application在 MVC Core 应用程序中运行迁移时出错
【发布时间】:2017-01-03 15:33:04
【问题描述】:

我正在尝试运行以下命令来为我自己创建的上下文创建新的迁移。我运行这个命令。

dotnet ef migrations add MusicContextCreation --context MusicContext

这是我的音乐上下文课程。这就是我尝试添加迁移的目的。

using Microsoft.EntityFrameworkCore;

namespace MusicianProject.Models.Contexts
{
    public class MusicContext : DbContext
    {
        public MusicContext(DbContextOptions<MusicContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            //builder.Entity<Band>().HasMany<BandMember>();
            //builder.Entity<Band>().HasMany<Album>(band => band.Albums);
            builder.Entity<Band>().ToTable("Band");
            //builder.Entity<BandMember>().HasOne<User>(bandmember => bandmember.User);
            builder.Entity<BandMember>().ToTable("BandMember");
            builder.Entity<Album>().ToTable("Album");
            builder.Entity<Genre>().ToTable("Genre");
        }

        public DbSet<Band> Bands { get; set; }
        public DbSet<Genre> Genres { get; set; }
        public DbSet<BandMember> BandMembers { get; set; }
        public DbSet<Album> Albums { get; set; }

    }
}

这是我在运行该命令时在命令提示符中收到的错误消息。

实体类型 Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin 需要定义主键。

我不明白的是,我将基类称为 OnModelCreating,我在其他类似问题中将其视为答案。我不明白的是,我为身份用户提供的另一个上下文并没有给我这个问题,它实际上设置了身份表。

如果需要,我可以添加在此上下文中使用的类,我还没有添加它们,因为我不想弄乱。如果需要查看在 dbset 集合中定义的类,请在 cmets 中告诉我。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    您应该从IdentityDbContext(而不是DbContext)继承,它具有适当的OnModelCreating 内容和身份类的流畅配置。

    如果您想拥有两个不同的 DbContext,一个用于用户,另一个用于其他类 - 您不应该在不同上下文中的类之间有任何引用,请阅读 my answer here

    【讨论】:

    • 我将类更改为从 IdentityDbContext 继承,但仍然出现相同的错误。您是否建议我将 DbSet 移动到我的 IdentityDbContext 中?我不明白为什么他们必须分开。
    • 你的意思是“我的 IdentityDbContext”?您应该从 Microsoft.AspNetCore.Identity.EntityFramework 命名空间中的一个继承,请参阅 here
    • 对不起,我的意思是我的“UserContext”类。我将我的 MusicContext 更改为从 IdentityDbContext 继承,但它仍然无法正常工作。所以我注释掉了乐队和乐队成员集,它起作用了(我认为这是因为他们引用了我的继承自 IdentityUser 的用户类)。
    • 这清楚地表明您在继承用户和其他身份类时有问题,因为当您删除对它们的所有引用时(评论 BandBandMember) - 您的 DbContext 有效。如果不查看所有涉及的代码,很难说出究竟是什么问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2017-12-17
    • 2016-08-17
    相关资源
    最近更新 更多