简体   繁体   中英

EF code first table relationships

I'm trying to learn EF using code first, i dont know how to design properly using this method. Please help me

My classes looks like this

public class Item
{
  public int ItemID{ get; set; }

  public string Name { get; set; }
  public int StockUnitOfMeasure{ get; set; }
  public int PurchaseUnitOfMeasure{ get; set; }
}

public class UnitOfMeasure 
{
  public int UnitOfMeasureID { get; set; }
  public string MeasureName { get; set; }
}

I want to have the StockUnitOfMeasure and PurchaseUnitOfMeasure to be the foreign key.

Here's he sample data

ItemID      Name    StockUnitOfMeasure  PurchaseUnitOfMeasure
1          Apples     2                     1
2          Milk       3                     4

UnitOfMeasureID      MeasureName 
1                    Piece
2                    Dozen
3                    Box
4                    Packs

meaning: 
apples are stocked at the warehouse by DOZEN, but will be purchased per PIECE
Milks  are stocked at the warehouse by BOX, but will be purchased per PACK

For clarity and conventions I have suffixed the FK properties with Id . You can rename these to suite your need.

public class Item
{
  public int ItemID { get; set; }

  public string Name { get; set; }

  public int StockUnitOfMeasureId { get; set; }
  public UnitOfMeasure StockUnitOfMeasure { get; set; }

  public int PurchaseUnitOfMeasureId { get; set; }
  public UnitOfMeasure PurchaseUnitOfMeasure { get; set; }
}

class MyContext : DbContext
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Item>().HasRequired(x => x.StockUnitOfMeasure)
           .WithMany()
           .HasForeignKey(x => x.StockUnitOfMeasureId).WillCascadeOnDelete(true);

        modelBuilder.Entity<Item>().HasRequired(x => x.PurchaseUnitOfMeasure)
           .WithMany()
           .HasForeignKey(x => x.PurchaseUnitOfMeasureId).WillCascadeOnDelete(true); 

      base.OnModelCreating(modelBuilder);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM