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