【发布时间】:2012-08-23 21:50:08
【问题描述】:
我正在尝试在 EF 中创建一个关系,其中外键是可选的。例如像: https://stackoverflow.com/a/6023998/815553
我的问题是,有什么方法可以做类似上述的事情,但我可以在哪里保留 ContactID 属性作为模型的一部分?
在我的具体情况下,我有一个 Person 和一个 Voucher。 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
};
【问题讨论】:
标签: c# entity-framework