EFCore-一对一配置外键小记

前后两次遇到这样的错误:

The property 'xx' on entity type 'xxxx' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

多数情况下是表配置关系会出现这样的问题。我实在配置TagItem一对一关联TagUseCount出现的问题:

public void Configure(EntityTypeBuilder<TagItem> builder)
        {
            builder.ToTable("Tags")
                .HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("TagId");
            builder.Property(x => x.TagName);

            builder.HasOne(x => x.TagUseCount)
                .WithOne(x => x.Tag)
                .HasForeignKey<Tag>(x => x.Id);
        }

以及

public void Configure(EntityTypeBuilder<TagUseCount> builder)
        {
            builder.ToTable("TagUseCount");

            builder.Property(t => t.Id)
                .HasColumnName("TagId");
            builder.Property(t => t.UseCount);
        }

以上配置有两点错误,都是调试后总结出来的:

  1. TagItem 关联TagUseCount 需要指定的是关联表的外键,也就是TagUseCountId,不能指定自己哦!
  2. TagUseCount千万别偷懒或忘记写 builder.HasKey(x => x.Id);
posted @ 2019-08-19 13:21  ohyex  阅读(2516)  评论(0编辑  收藏  举报