I have 2 classes Bill and BillType. Each Bill should have a BillType and TypeId should be a FK. Using Code First, a column is added to my database table Bills called BillType_TypeId that has a FK relationship with the table BillTypes.
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; }
}
My problem comes when I need to insert a TypeId into the Bills table. I’ve been using this code to insert:
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;
}
}
There isn’t an exposed object make equal to int billType. I’m not sure how to add it while still maintaining the FK constraints. How do I accomplish this. Also, I’m using Entity Framework 5.
You could update your class to expose the BillType reference:
then your create:
If you don’t want to expose the reference of the BillType on the bill, you could also add a fluent mapping: