Marco Leo
Marco Leo

Reputation: 516

Ef code first Mapping

I have a strange situation

I have 3 entities:

public class Product
{
   public virtual int id {get;set;}
}

public class Media
{
   public virtual ICollection<MediaProduct> mediaProducts {get;set;}
}

public class MediaProduct 
{
   public virtual int id {get;set;}
   public virtual Media media {get;set;}
   public virtual Product product {get;set;}

   public virtual int productId { get; set; }
   public virtual int mediaId { get; set; }
}

As you can see in my product entity I don't have a reference to MediaProduct, and i can't change that.

I dont't know how I can Map those entities.

My class for the mapping is

public class MediaProcutMap : EntityTypeConfiguration<MediaProduct>
    {
        public MediaProcutMap()
        {
            this.ToTable("Media_Product_Mapping");
            this.HasKey(pc => pc.Id);

            this.HasRequired(pc => pc.media)
                .WithMany(c => c.mediaProducts)
                .HasForeignKey(pc => pc.mediaId);

            //this.HasRequired(pc => pc.product) ???                
        }
    }

but it isn't working

please help me

Marco

Upvotes: 0

Views: 224

Answers (1)

Eranga
Eranga

Reputation: 32437

There is an overload of WithMany that does not take a parameter.

public class MediaProcutMap : EntityTypeConfiguration<MediaProduct>
{
        public MediaProcutMap()
        {
            this.ToTable("Media_Product_Mapping");
            this.HasKey(pc => pc.Id);

            this.HasRequired(pc => pc.media)
                .WithMany(c => c.mediaProducts)
                .HasForeignKey(pc => pc.mediaId);

            this.HasRequired(pc => pc.product).
                .WithMany()
                .HasForeignKey(pc => pc.productId);              
        }
 }

Upvotes: 1

Related Questions