为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
函数式编程 2024-01-20 16:08:54
我需要在 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,我收到此错误:值不能为空。(参数“键”)有什么问题?我该如何解决这个问题?
查看完整描述

2 回答

?
料青山看我应如是

TA贡献1772条经验 获得超7个赞

这是因为您的实体之一(继承自接口:)IEntity没有标识列。


请检查您的所有实体。确保他们都有一个 ID 或标记为 的属性[Key]。


public class MyEntity : IEntity

{

    // make sure:

    public int Id { get; set; }

    // or:

    [Key]

    public int SomeProperty { get; set; }

}


查看完整回答
反对 回复 2024-01-20
?
米脂

TA贡献1836条经验 获得超3个赞

仅对于注册而言,当从现有表创建 UniqueKey 并且 UniqueKey 字段之间已存在重复记录时,这种情况也会发生在 DDD 中。


例子:


//SQL: [dbo].[User]:

Id | Name | Login

1  | Thi  | thi.xpto

2  | Thi  | thi.xpto



[Table("User")]

public class User

{

  [Key]

  public int Id { get; set; }

  public string Name { get; set; }

  public string Login { get; set; }

}


public class UserDbContext : DbContext

{

  ...

  protected override void OnModelCreating(ModelBuilder modelBuilder)

  {

    modelBuilder.Entity<User>()

      .HasAlternateKey(x => new { x.Name, x.Login })

      .HasName("UK_User_NameLogin");

  }

}


查看完整回答
反对 回复 2024-01-20
  • 2 回答
  • 0 关注
  • 33 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信