简体   繁体   中英

EF Core One-to-One entity mapping using shared key with Fluent API

I configure my One-to-Many relationships using this method:

private void ConfigureRelationshipOneToMany<E, T>(ModelBuilder builder, string key, Expression<Func<E, T>> propertyMapping) where E : class where T : class {
    builder.Entity<E>()
        .Property<string>(key);

    builder.Entity<E>()
        .HasOne(propertyMapping)
        .WithMany()
        .HasForeignKey(key);
}
ConfigureRelationshipOneToMany<ProductStyle, ProductGroup>(builder, "ProductGroupCode", s => s.ProductGroup);
public class ProductStyle {
    [Key]
    public string Code { get; set; }
    public string Name { get; set; }
    public ProductGroup ProductGroup { get; set; }
}
public class ProductGroup {
    [Key]
    public string Code { get; set; }
    public string Name { get; set; }
}

This works fine and all of my relationships are correctly configured with Shadow Properties for the foreign keys. I'm trying to implement the equivalent for One-to-Many relationships like this:

private void ConfigureRelationshipOneToOne<E, T>(ModelBuilder builder, string key, Expression<Func<E, T>> propertyMapping, Expression<Func<T, E>> returnMapping) where E : class where T : class {
    builder.Entity<T>()
        .Property<string>(key);

    builder.Entity<E>()
        .HasOne(propertyMapping)
        .WithOne(returnMapping)
        .HasForeignKey(key);
}
ConfigureRelationshipOneToOne<Product, ProductDimensions>(builder, "SKU", p => p.Dimensions, d => d.Product);

The product class already has a property "SKU" which is the primary key. When I try to add a migration I get this error:

System.InvalidOperationException: You are configuring a relationship between 'ProductDimensions' and 'Product' but have specified a foreign key on 'SKU'. The foreign key must be defined on a type that is part of the relationship.

My goal is to have a bi-directional mapping between Product and ProductDimensions on the SKU field without having to have a SKU property on the ProductDimensions class. How can I achieve this?

private void ConfigureRelationshipOneToOne<E, T>(ModelBuilder builder, string key, Expression<Func<E, T>> propertyMapping, Expression<Func<T, E>> returnMapping) where E : class where T : class {
    builder.Entity<T>()
        .Property<string>(key);

    builder.Entity<T>()
        .HasKey(key);

    builder.Entity<E>()
        .HasOne(propertyMapping)
        .WithOne(returnMapping)
        .HasForeignKey<T>(key);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM