Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map weak entity by using Code first

Hi I have developed model that works perfectly for me, now I want to map it to database using EntityFramework, here is a part of it:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ProductType Type { get; set; }
}

public class Supplier
{
    public int Id { get; set; }
    public string OIB { get; set; }
    public string Name { get; set; }
}

public class SupplierProduct
{
    public double Price { get; set; }
    public string SupplierMark { get; set; }

    public virtual Product Product { get; set; }
    public virtual Supplier Supplier { get; set; }
}

Now my question is how do I write entity configuration on ModelBuilder form my DBContext so that it maps on SupplierProduct class ForeignKeys Supllier.ID and Product.Id as Primary key of DB relation.

like image 680
MrTommek Avatar asked Dec 30 '25 10:12

MrTommek


1 Answers

I use data annotations, but I expect you're looking for the following:

define ID properties for Product and Supplier in SupplierProduct, specify these ID fields as FK's, then define compound primary key with the two ID fields

modelBuilder.Entity<SupplierProduct>()
    .HasRequired( sp => sp.Product)
    .WithMany( p => SupplierProducts )
    .HasForeignKey( sp => sp.ProductId );

modelBuilder.Entity<SupplierProduct>()
    .HasRequired( sp => sp.Supplier)
    .WithMany( s => SupplierProducts )
    .HasForeignKey( sp => sp.SupplierId );

modelBuilder.Entity<SupplierProduct>()
    .HasKey(sp=> new { sp.ProductId, sp.SupplierId });
like image 73
Moho Avatar answered Jan 01 '26 22:01

Moho