值不能为空。ASP.NET Core 3..0 中的(参数“key”)

我需要在 ASP.NET Core 3.0 中使用代码优先创建一个数据库


这是DbContext:


public class TrelloContext : DbContext

{

    public TrelloContext(DbContextOptions options) : base(options)

    {

    }


    protected override void OnModelCreating(ModelBuilder modelBuilder)

    {

        base.OnModelCreating(modelBuilder);

        modelBuilder.AddDbSet<IEntity>(typeof(IEntity).Assembly);

        modelBuilder.ApplyConfigurationsFromAssembly(typeof(IType).Assembly);

    }

}

这是启动:


public void ConfigureServices(IServiceCollection services)

{

        services.AddControllers().AddControllersAsServices();

        services.AddDbContext<TrelloContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));

        services.Injection();

}

这是我的连接字符串:


"ConnectionStrings": {

    "SqlServer": "Data Source=.;Initial Catalog=TrelloDB;Trusted_Connection=True;Trusted_Connection=True;"

}

当我使用这个时add-migration initial,我收到此错误:


值不能为空。(参数“键”)


有什么问题?我该如何解决这个问题?


函数式编程
浏览 36回答 2
2回答

料青山看我应如是

这是因为您的实体之一(继承自接口:)IEntity没有标识列。请检查您的所有实体。确保他们都有一个 ID 或标记为 的属性[Key]。public class MyEntity : IEntity{&nbsp; &nbsp; // make sure:&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; // or:&nbsp; &nbsp; [Key]&nbsp; &nbsp; public int SomeProperty { get; set; }}

米脂

仅对于注册而言,当从现有表创建 UniqueKey 并且 UniqueKey 字段之间已存在重复记录时,这种情况也会发生在 DDD 中。例子://SQL: [dbo].[User]:Id | Name | Login1&nbsp; | Thi&nbsp; | thi.xpto2&nbsp; | Thi&nbsp; | thi.xpto[Table("User")]public class User{&nbsp; [Key]&nbsp; public int Id { get; set; }&nbsp; public string Name { get; set; }&nbsp; public string Login { get; set; }}public class UserDbContext : DbContext{&nbsp; ...&nbsp; protected override void OnModelCreating(ModelBuilder modelBuilder)&nbsp; {&nbsp; &nbsp; modelBuilder.Entity<User>()&nbsp; &nbsp; &nbsp; .HasAlternateKey(x => new { x.Name, x.Login })&nbsp; &nbsp; &nbsp; .HasName("UK_User_NameLogin");&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP