Home > Net >  EF Core Mapping one field of an object to two diffrent fields of another object
EF Core Mapping one field of an object to two diffrent fields of another object

Time:06-16

I have a Currency object and a Product object. I need to link the Currency to WholesaeCurrency as well as RetailCurrency fields of the Product object

public class Currency
    {
        /// <summary>
        /// Id is the 3 character ISO currency code
        /// </summary>
        [StringLength(3)]
        public string Id { get; set; }

        [StringLength(100)]
        public string Name { get; set; }
    }

I have another object with 2 currency fields:

public class Product
    {
        public int Id { get; set; }

        public decimal WholesaleRate { get; set; }
        public string WholesaleCurrencyId { get; set; }
        public virtual Currency WholesaleCurrency { get; set; }

        public decimal RetailRate { get; set; }
        public string RetailCurrencyId { get; set; }
        public virtual Currency RetailCurrency { get; set; }
    }

My queries are:

  1. What is the relation between these 2 objects? one-to-many or one-to-one?
  2. How do I express these relations? Is the above correct?

CodePudding user response:

You can try the below demo:

In Currency:

public class Currency
 {
        /// <summary>
        /// Id is the 3 character ISO currency code
        /// </summary>
        [StringLength(3)]
        public string Id { get; set; }

        [StringLength(100)]
        public string Name { get; set; }

        public virtual ICollection<Product> ProductWholesale { get; set; }
        public virtual ICollection<Product> ProductRetail { get; set; }
    }

In Product:

public class Product
    {
        public int Id { get; set; }

        public decimal WholesaleRate { get; set; }
        public string WholesaleCurrencyId { get; set; }
        public virtual Currency WholesaleCurrency { get; set; }

        public decimal RetailRate { get; set; }
        public string RetailCurrencyId { get; set; }
        public virtual Currency RetailCurrency { get; set; }
    }

In your context add below code:

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>()
                .HasOne(p => p.WholesaleCurrency)
                .WithMany(t => t.ProductWholesale)
                .HasForeignKey(m => m.WholesaleCurrencyId )
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<Product>()
                .HasOne(p => p.RetailCurrency)
                .WithMany(t => t.ProductRetail)
                .HasForeignKey(m => m.RetailCurrencyId)
                .OnDelete(DeleteBehavior.Restrict);
        }

Result:

enter image description here

  • Related