【问题标题】:C# EF Code First 1:1 optional relationship foreign key propertyC# EF Code First 1:1 可选关系外键属性
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多