Search code examples
c#database.net-coreef-code-first

How to add relationship beetween two different libraries in .NET Core


I need build a link between two libraries in .NET Core using the code-first approach.

I need to build a link between the countries table from the standards library and the table with trade forms.

Both libraries operate on separate contexts.

Relationships between projects can be added unidirectionally because if you try to add a bidirectional constraint, you get a circular error.

Is there any way to build such a relationship?

public class CountryStandard
{
    [Key]
    public int IdCountryStandard { get; set; }
    [Required(ErrorMessage = "Select Country")]
    [Display(Name = "Name Country")]
    [MaxLength(80, ErrorMessage = "Name max 80")]
    public string NameCountryStandard { get; set; }
    public bool IsActive { get; set; }
    [JsonIgnore]
    //public virtual Standard Standard { get; set; }
    public virtual ICollection<Standard> Standard { get; set; }
    public virtual ICollection<TradeForms> TradeForms { get; set; }
}

public class TradeForms
{
    [Key]
    public int TradeFormsId { get; set; }
    /...
    .../
    public int IdCountryStandard { get; set; }
    public CountryStandard CountryStandard { get; set; }
}

After building the relationship, I would add to the Fluent API And he did the database migration.

But I don't know if it is possible to build relationships between separate libraries from code-first in this way.

enter image description here


Solution

  • No, it isn't possible to do circular referencing in .NET.

    Solution 1 I recommend

    Merge Standard.DAL and Trade.DAL in one project DAL.

    Solution 2

    Remove in Standard.DAL all reference to Trade.DAL. For example with CountryStandard :

    public class CountryStandard
    {
        [Key]
        public int IdCountryStandard { get; set; }
        ...
        public virtual ICollection<Standard> Standard { get; set; }
        // Remove - public virtual ICollection<TradeForms> TradeForms { get; set; }
    }
    

    Solution 3

    If you really need this navigation property, you can apply the solution 2 and extend standard entities to add removed navigation properties. For example with Standard.DAL.CountryStandard, you can extend in the Trade.DAL project to :

    namespace Trade.DAL
    {
        public class TradeCountry : CountryStandard
        {
            public ICollection<TradeForms> TradeForms { get; set; }
        }
    }
    

    Then in the context :

    namespace Trade.DAL
    {
        public class TradeEntities : DbContext
        {
            ...
    
            public DbSet<TradeForms> TradeForms { get; set; }
            public DbSet<TradeCountry> TradeCountries { get; set; }
        }
    }