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);
}
以上配置有两点错误,都是调试后总结出来的:
TagItem
关联TagUseCount
需要指定的是关联表的外键,也就是TagUseCount
的Id
,不能指定自己哦!TagUseCount
千万别偷懒或忘记写builder.HasKey(x => x.Id);