EF代码第一个表关系

时间:2012-03-25 09:28:58

标签: c# entity-framework ef-code-first

我正在尝试首先使用代码学习EF,我不知道如何使用此方法正确设计。请帮帮我

我的课程看起来像这样

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; }
}

我想让StockUnitOfMeasurePurchaseUnitOfMeasure成为外键。

这是他的样本数据

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

1 个答案:

答案 0 :(得分:1)

为了清晰和约定,我使用Id为FK属性添加了后缀。您可以重命名这些以满足您的需求。

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);
    }
}