2012-10-18 64 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);