I have two tables products and relationships.
Product:
public int Id {get; set;} //primary key
public string Name {get; set;}
public int Availability {get; set;}
Relationship:
public int Id {get; set;} //primary key
public string RelationshipName {get; set;}
Primary key of Relationship table to be set as foreign key in the Product. It is a one to one relationship. For entity framework core to generate migration, I have added a new property in both the tables as below
Product:
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;}
Relationship:
public int Id {get; set;} //primary key
public string RelationshipName {get; set;}
///Added new property
public virtual Product Product
RelationshipConfiguration is as below:
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>();
}
Product Configuration is as below:
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
}
How to set the foreign key configuration with relationship in Product table? Need to set HasOne, WithOne, ForeignKey Relationship in Product Configuration? Should it be
builder.HasOne(x => x.Relationship) .WithOne(x => x.Product) .HasForeignKey(x => x.Id);
// but this lead to having no property in Product to hold the foreign key value of Relationship
or
do I need to add another property in Product like
public int RelationshipId {get; set;}
and the configuration to be
builder.HasOne(x => x.Relationship)
.WithOne(x => x.Product)
.HasForeignKey<Product>(x => x.RelationshipId);
Can you please suggest what is the approach for configuring one to one relationship? And also adding a new property in each table the right approach?
Thanks in advance.