如何插入外键

时间:2012-10-18 14:49:04

标签: entity-framework

我有两个类Bill和BillType。每个Bill都应该有一个BillType,TypeId应该是FK。使用Code First,将一列添加到我的数据库表中名为BillType_TypeId的Bills,它与表BillTypes具有FK关系。

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

当我需要将TypeId插入Bills表时,我的问题出现了。我一直在使用这段代码插入:

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约束的同时添加它。我该如何做到这一点。另外,我正在使用Entity Framework 5。

1 个答案:

答案 0 :(得分: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);