Entity framework 如何插入外键
我有两门课比尔和比尔类型。每张票据都应该有一个BillType,TypeId应该是FK。首先使用代码,将一列添加到我的数据库表Bills中,称为BillType_TypeId,它与表BillTypes具有FK关系Entity framework 如何插入外键,entity-framework,Entity Framework,我有两门课比尔和比尔类型。每张票据都应该有一个BillType,TypeId应该是FK。首先使用代码,将一列添加到我的数据库表Bills中,称为BillType_TypeId,它与表BillTypes具有FK关系 public class Bill { [Key] public int BillId { get; set; } [Required, MaxLength(100)] public string Name { get; set; } [Re
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; }
}
公共类法案
{
[关键]
公共int BillId{get;set;}
[必需,最大长度(100)]
公共字符串名称{get;set;}
[必需]
公共十进制数{get;set;}
public System.DateTime DueDate{get;set;}
[必需]
公共Guid用户标识{get;set;}
}
公共类BillType
{
[关键]
公共int类型ID{get;set;}
[必需,最大长度(100)]
公共字符串名称{get;set;}
公共虚拟列表{get;set;}
}
当我需要在Bills表中插入一个TypeId时,我的问题就出现了。我一直在使用此代码插入:
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;
}
}
public类动作
{
私有BillContext_db=new BillContext();
公共布尔InsertNewBill(int-billType、字符串名称、十进制金额、DateTime-dueDate、Guid-userId)
{
var票据=新票据{
xxx您可以更新您的类以公开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的引用,还可以添加一个fluent映射:
modelBuilder.Entity<BillType>()
.HasMany(bt => bt.Bills)
.WithOptional()
.HasForeignKey(bt => bt.BillTypeId);
modelBuilder.Entity()
.HasMany(bt=>bt.Bills)
.WithOptional()
.HasForeignKey(bt=>bt.BillTypeId);