1

I am trying to create a relationship in EF where the foreign key is optional. For example like: https://stackoverflow.com/a/6023998/815553

My question is, is there any way to do something like the above but where I can keep the ContactID property as part of the model?

In my specific case I have a Person and a Voucher. The person table will have a VoucherId which is optional, as the voucher will only come in at a later stage to link up to the person.

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"));

What I have here works, but what I want is yo have VoucherId in the Person class. As it stands in order to add a voucher to the person I have to give the entire Voucher object to the Voucher parameter.

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();
}

I want to be able to do:

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
};
Community
  • 1
  • 1
David Esteves
  • 1,614
  • 2
  • 15
  • 22

1 Answers1

3

You can create the FK mapping like this:

   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; }
   }
Mark Oreta
  • 10,346
  • 1
  • 33
  • 36