1

我正在尝试在 EF 中创建一个关系,其中外键是可选的。例如像: https ://stackoverflow.com/a/6023998/815553

我的问题是,有没有办法做类似上述的事情,但我可以在哪里将 ContactID 属性作为模型的一部分?

在我的具体情况下,我有一个人和一个凭证。person 表将有一个可选的 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。就目前而言,为了向该人添加凭证,我必须将整个 Voucher 对象提供给 Voucher 参数。

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

1 回答 1

3

您可以像这样创建 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; }
   }
于 2012-08-24T01:04:59.807 回答