我有两个表产品和关系。
产品:
public int Id {get; set;} //primary key
public string Name {get; set;}
public int Availability {get; set;}
关系:
public int Id {get; set;} //primary key
public string RelationshipName {get; set;}
将关系表的主键设置为产品中的外键。它 是一对一的关系。 为了使实体框架核心生成迁移,我添加了一个新属性 在下面的两个表中
产品:
public int Id {get; set;} //primary key
public string Name {get; set;}
public int Availability {get; set;}
/// Added new property
public virtual Relationship Relationship {get; set;}
关系:
public int Id {get; set;} //primary key
public string RelationshipName {get; set;}
///Added new property
public virtual Product Product
RelationshipConfiguration如下:
public void Configure(EntityTypeBuilder<Relationship> builder)
{
builder.ToTable("Relationship");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id)
.IsRequired()
.HasMaxLength(DataConstants.KeyStringLength)
.IsRequired()
.IsFixedLength()
.HasValueGenerator<SequentialGuidStringValueGenerator>();
}
产品配置如下:
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("Product");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id)
.IsRequired()
.HasMaxLength(DataConstants.KeyStringLength)
.IsRequired()
.IsFixedLength()
.HasValueGenerator<SequentialGuidStringValueGenerator>();
//how do I set the foreign key configuration with relationship here
}
如何在Product表中设置具有关系的外键配置?需要设置HasOne, WithOne,产品配置中的外键关系? 应该是
builder.HasOne(x => x.Relationship) .WithOne(x => x.Product) .HasForeignKey(x => x.Id);
//,但这导致产品中没有属性来保存Relationship的外键值
或
我是否需要在Product之类的商品中添加另一个属性
public int RelationshipId {get; set;}
和要配置的
builder.HasOne(x => x.Relationship)
.WithOne(x => x.Product)
.HasForeignKey<Product>(x => x.RelationshipId);
您能否建议配置一对一关系的方法是什么?还要在每个表中添加新属性正确的方法吗?
谢谢。