Randy
Randy

Reputation: 1287

How do I configure a Fluent Compound ForeignKey on a One-to-One mapping

I have three Entity Models:

Orders:

[Table("SOP10100")]
public class Order
{
    [Column("SOPTYPE")]
    public short Soptype { get; set; }

    [Column("SOPNUMBE")]
    [StringLength(21)]
    public string Sopnumbe { get; set; }        
    ...
    public ICollection<OrderDetail> Details { get; set; }

    public ReservedDocument ReservedDocument { get; set; }
}

Details:

[Table("SOP10200")]
public partial class OrderDetail
{
    [Column("SOPTYPE")]
    public short Soptype { get; set; }
    
    [Column("SOPNUMBE")]
    [StringLength(21)]
    public string Sopnumbe { get; set; }
    
    [Column("LNITMSEQ")]
    public int Lnitmseq { get; set; }
    
    [Column("CMPNTSEQ")]
    public int Cmpntseq { get; set; }
    ...
    public Order Order { get; set; }
}

And ReservedDocuments:

[Table("ReservedDocuments", Schema = "cp")]
public partial class ReservedDocument
{
    [Column("SOPNUMBER")]
    [StringLength(21)]
    public string Sopnumber { get; set; }
    
    [Column("SOPTYPE")]
    public short Soptype { get; set; }
    ...
    public Order Order { get; set; }
}

In my DbContext's OnModelCreating Method I have:

        modelBuilder.Entity<Order>()
            .HasKey(x => new { x.Sopnumbe, x.Soptype });

        modelBuilder.Entity<Order>()
            .HasMany(d => d.Details)
            .WithOne(o => o.Order)
            .HasForeignKey(k => new {k.Sopnumbe, k.Soptype});

        modelBuilder.Entity<Order>()
            .HasOne(d => d.ReservedDocument)
            .WithOne(o => o.Order)
            .HasForeignKey(x => new {x.Sopnumbe, x.Soptype}); <<== Compiler Error CS1660

        modelBuilder.Entity<OrderDetail>()
            .HasKey(x => new { x.Sopnumbe, x.Soptype, x.Cmpntseq, x.Lnitmseq });

        modelBuilder.Entity<ReservedDocument>()
            .HasKey(x => new { x.Sopnumber, x.Soptype });

Visual Studio 2019 has red squiggly lines under my One-to-One mapping for Order to ReserveDocument HasForeignKey for Compiler Error CS1660.

What do I need to do to fix this? It is working for OrderDetail.

Upvotes: 0

Views: 39

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89051

Because the Foreign Key could be on either entity, you have to specify the type to get the Foreign Key property, and you do that by specifying the type parameter for the dependent type. So try:

        modelBuilder.Entity<Order>()
            .HasOne(d => d.ReservedDocument)
            .WithOne(o => o.Order)
            .HasForeignKey<ReservedDocument>(x => new { x.Sopnumber, x.Soptype }); 

or if you want the FK on Order you can specify that:

        modelBuilder.Entity<Order>()
            .HasOne(d => d.ReservedDocument)
            .WithOne(o => o.Order)
            .HasForeignKey<Order>(x => new { x.Sopnumbe, x.Soptype }); 

Upvotes: 1

Related Questions