Is it possible to set up a navigation property without the foreign key?

.net .net-core c# entity-framework entity-framework-core

Question

Is it possible to have two (or more) navigation properties of the same type?

My model looks like this...

public class Agreement
{
    public int Id { get; set; }
    public Guid? BuyerId { get; set; }
    public Guid? SellerId { get; set; }

    public AgreementInfo ByerAgreementInfo { get; set; }
    public AgreementInfo SellerAgreementInfo { get; set; }
}

public class AgreementInfo
{
    // PK is AgreementId and OwnerActorId combined.
    public int AgreementId { get; set; }
    public Guid OwnerActorId { get; set; }
    public string Name { get; set; }
}

... and i'm trying to include the navigation properties by matching the AgreementId and the ByerId/SellerId...

modelBuilder.Entity<Agreement>().HasOne(x => x.ByerAgreementInfo).WithOne().HasForeignKey<Agreement>(x => new {x.Id, x.ProviderId});
modelBuilder.Entity<Agreement>().HasOne(x => x.SellerAgreementInfo).WithOne().HasForeignKey<Agreement>(x => new { x.Id, x.RequesterId });

... but this results in a circural dependecy.

Is there any way to include these properties without using a foreign key? Or is there another solution (except for adding an id-column to the info table) that allows me to use the info-table rows as navigation properties in the agreement class?

1
2
7/12/2019 3:20:04 AM

Popular Answer

... but this results in a circural dependecy

Yes! It will. To overcome this you have to specify .OnDelete(DeleteBehavior.Restrict); in your Fluent API configuration as follows but first you have to write your Agreement model class as follows too:

public class Agreement
{
    public int Id { get; set; }
    public Guid? BuyerId { get; set; }
    public Guid? SellerId { get; set; }

    public int AgreementIdForBuyer { get; set; }
    public Guid OwnerActorIdForBuyer { get; set; }

    public int AgreementIdForSeller { get; set; }
    public Guid OwnerActorIdForSeller { get; set; }

    public AgreementInfo ByerAgreementInfo { get; set; }
    public AgreementInfo SellerAgreementInfo { get; set; }
}

Now in Fluent API configuration:

modelBuilder.Entity<Agreement>()
    .HasOne(x => x.ByerAgreementInfo)
    .WithOne()
    .HasForeignKey<Agreement>(p => new {p.AgreementIdForBuyer, p.AgreementIdForBuyer})
    .OnDelete(DeleteBehavior.Restrict); // <-- Here it is

modelBuilder.Entity<Agreement>()
    .HasOne(x => x.SellerAgreementInfo)
    .WithOne()
    .HasForeignKey<Agreement>(p => new {p.AgreementIdForSeller, p.OwnerActorIdForSeller})
    .OnDelete(DeleteBehavior.Restrict); // <-- Here it is
0
7/12/2019 3:17:20 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow