'Creating one to one Navigation Property without foreign key
I am trying to query a table using navigation property from another table. The data has a shared key (like a foreign key) however it is not specified that way in the database. Entity framework core however gives me a The foreign key must target a type that is part of the relationship error. So my question is, how can I declare a navigational property for a one to one relation and use it as such?
public class ParentEntityConfiguration : IEntityTypeConfiguration<Parent>
{
public void Configure(Entity TypeBuilder<Parent> builder)
{
builder.HasKey(e => e.InvoiceNumber);
builder.ToTable("Parent");
builder.Property(e => e.InvoiceNumber).HasColumnName("InvoiceNumber");
builder.Property(e => e.InvoiceGroup).HasColumnName("InvoiceGroup");
builder.HasOne(e => e.Child).WithOne(x=>x.Parent).HasPrincipalKey("InvoiceGroup").HasForeignKey("AccountNumber");
}
}
public class Parent
{
DbContext _dbContext;
public Parent(DbContext dbContext)
{
_dbContext=dbContext
}
public string InvoiceNumber {get;set;}
public string InvoiceGroup {get;set;}
public Child Child {get;set;}
}
public class ChildEntityConfiguration : IEntityTypeConfiguration<Child>
{
public void Configure(Entity TypeBuilder<Child> builder)
{
builder.HasKey(e => e.Id);
builder.ToTable("Child");
builder.Property(e => e.Id).HasColumnName("Id");
builder.Property(e => e.AccountNumber).HasColumnName("AccountNumber");
}
}
public class Child
{
DbContext _dbContext;
public Child(DbContext dbContext)
{
_dbContext=dbContext
}
public string Id {get;set;}
public string AccountNumber {get;set;}
public Parent Parent {get;set;}
}
StackTrace:
You are configuring a relationship between 'Parent' and 'Child', but have specified a foreign key targeting 'InvoiceGroup'.
The foreign key must target a type that is part of the relationship.
at Microsoft.EntityFrameworkCore.Metadata.Builders.ReferenceReferenceBuilder.HasPrincipalKeyBuilder(EntityType principalEntityType, String principalEntityTypeName, Func`2 hasPrincipalKey)
at Microsoft.EntityFrameworkCore.Metadata.Builders.ReferenceReferenceBuilder.HasPrincipalKeyBuilder(EntityType principalEntityType, String principalEntityTypeName, IReadOnlyList`1 foreignKeyPropertyNames)
at Microsoft.EntityFrameworkCore.Metadata.Builders.ReferenceReferenceBuilder`2.HasPrincipalKey (String principalEntityTypeName, String[] keyPropertyNames)
at Models.Data.Config.ParentEntityConfiguration.Configure(EntityTypeBuilder`1 builder)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
