2012-10-18 99 views
0

我有2類Bill和BillType。每個法案應該有一個BillType和TypeId應該是一個FK。使用代碼首先,將一列添加到我的數據庫表格Bill Bill_TypeId中,該表格與BillType表格具有FK關係。當我需要插入的typeid到票據表格如何插入到外鍵

public class Bill 
{ 
    [Key] 
    public int BillId { get; set; } 

    [Required, MaxLength(100)] 
    public string Name { get; set; } 

    [Required] 
    public decimal Amount { get; set; } 

    public System.DateTime DueDate { get; set; } 

    [Required] 
    public Guid UserId { get; set; } 
} 

public class BillType 
{ 
    [Key] 
    public int TypeId { get; set; } 

    [Required, MaxLength(100)] 
    public string Name { get; set; } 

    public virtual List<Bill> Bills { get; set; } 
} 

我的問題就來了。我一直在用這段代碼來插入:

public class BillActions 
{ 
    private BillContext _db = new BillContext(); 

    public Boolean InsertNewBill(int billType, string name, decimal amount, DateTime dueDate, Guid userId) 
    { 
     var bill = new Bill {     
      xxx        <-- problem is here 
      Name = name, 
      Amount = amount, 
      DueDate = dueDate, 
      UserId = userId 
     }; 

     _db.Bills.Add(bill); 

     _db.SaveChanges(); 
     return true; 
    } 
} 

沒有一個暴露的對象等於int billType。我不知道如何添加它,同時仍然保持FK限制。我如何做到這一點。另外,我使用實體框架5.

回答

1

你可以更新你的類暴露BillType參考:

public class Bill 
{ 
    [Key] 
    public int BillId { get; set; } 

    [Required, MaxLength(100)] 
    public string Name { get; set; } 

    [Required] 
    public decimal Amount { get; set; } 

    public System.DateTime DueDate { get; set; } 

    [Required] 
    public Guid UserId { get; set; } 

    public int BillTypeId {get;set;} 
    public BillType BillType {get;set;} 
} 

那麼你創建:

var bill = new Bill {     
     BillTypeId = billType, 
     Name = name, 
     Amount = amount, 
     DueDate = dueDate, 
     UserId = userId 
    }; 

如果你不想揭示帳單上BillType的參考,還可以添加流利的映射:

 modelBuilder.Entity<BillType>() 
      .HasMany(bt => bt.Bills) 
      .WithOptional() 
      .HasForeignKey(bt => bt.BillTypeId);