C#EF Code First 1:1可选关系外键属性

时间:2012-08-23 21:50:08

标签: c# entity-framework

我正在尝试在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
};

1 个答案:

答案 0 :(得分:2)

您可以像这样创建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; }
   }