Can a relationship one-to-one be created only one way?
public class Class1
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Class1Id { get; set; }
...
}
public class Class2
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Class2Id { get; set; }
public int? RelationshipId { get; set; }
public virtual Class1 Relationship { get; set; }
...
}
And the configuration looks like this
public void Configure(EntityTypeBuilder<Class2> builder)
{
builder.ToTable("...");
builder.HasOne(m => m.Relationship)
.WithOne()
.HasForeignKey<Class1>(a => a.Class1Id);
}
But when I try to inspect the Relationship in an instance of Class2 I get something wrong. The RelationshipId has a value and the Relationship.Class1Id has a different value. The Relationship.Class1Id has the same value as Class2Id.
Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?
Entity framework supports three types of relationships, same as database: 1) One-to-One 2) One-to-Many, and 3) Many-to-Many.
In a one-to-many relationship, each row of data in one table is linked to one or more rows in the second table. It is the most common type of relationship. A one-to-many relationship happens when the primary key of one table becomes foreign keys in another table.
To configure many-to-many relationship Using Data Annotations, you need to create the Join Table in the model. The Join Table BookCategory will have properties for the primary key of both the table. It will have two navigational properties one each for Book and Category class.
Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?
No. The mistake is in FK mapping:
.HasForeignKey<Class1>(a => a.Class1Id)
This way you are telling EF that it should use Class1Id
property of the Class1
as both PK and FK to Class2
, in which case the RelationshipId
property of Class2
is not treated as a FK, but like any other simple property.
Instead, you should specify the FK property of the relationship (1) is on Class2
and (2) is called RelationshipId
:
builder.HasOne(e => e.Relationship)
.WithOne()
.HasForeignKey<Class2>(e => e.RelationshipId);
// ^ ^
// (1) (2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With