[英]C# EF Code First 1:1 optional relationship foreign key property
我試圖在EF中創建一個關系,其中外鍵是可選的。 例如: https : //stackoverflow.com/a/6023998/815553
我的問題是,有沒有辦法像上面這樣做,但我可以將ContactID屬性作為模型的一部分?
在我的具體情況下,我有一個人和一張優惠券。 人員表將具有可選的VoucherId,因為優惠券將僅在稍后階段進入以鏈接到該人。
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public virtual Voucher Voucher { get; set; }
}
public class Voucher
{
public int ID { get; set; }
public string VoucherCode { get; set; }
}
modelBuilder.Entity<Person>()
.HasOptional(p => p.Voucher)
.WithOptionalDependent().Map(a => a.MapKey("VoucherId"));
我在這里工作,但我想要的是你在Person類中有VoucherId。 為了向人員添加憑證,我必須將整個憑證對象提供給憑證參數。
using (DatabaseContext context = new DatabaseContext())
{
Voucher v = new Voucher()
{
VoucherCode = "23423"
};
context.Voucher.Add(v);
context.SaveChanges();
Person p = new Person()
{
Name = "Bob",
Surname = "Smith",
Voucher=v
};
context.Person.Add(p);
context.SaveChanges();
}
我希望能夠做到:
Person p = new Person()
{
Name = "Bob",
Surname = "Smith",
VoucherId=v.ID // I wouldn't reference it like this, I would have the ID from a different source
};
您可以像這樣創建FK映射:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
[ForeignKey( "Voucher" )]
public int? VoucherId { get; set; }
public virtual Voucher Voucher { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.