EntityFramework:如何映射零对一关系?

时间:2015-11-19 10:47:49

标签: c# sql-server entity-framework

我有以下数据库表:

FundAllocation {below two columns make a composite primary key}
       [CurrencyRefId] (int)  {FK to a table Currency.CurrencyId}
       [AllocationRefId] (int) {FK to Allocation.AllocationId}

Allocation
       [AllocationId] (int) {PK Identity Column}
       [AllocationTitle] (varchar)

以下是与上表对应的实体:

public class FundAllocation
{
    [Key]
    [Column(Order = 1)]
    public int CurrencyRefId { get; set; }
    [Key]
    [Column(Order = 2)]
    public int AllocationRefId { get; set; }

    [ForeignKey("AllocationRefId")]
    public Allocation Allocation { get; set; }
}

public class Allocation
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AllocationId { get; set; }
    public string AllocationTitle { get; set; }
}

现在,当我从数据上下文中获取FundAllocation列表时,其Allocation属性设置为null。实现这种零对一关系还需要哪些其他配置?

1 个答案:

答案 0 :(得分:1)

要解决您的问题,您必须通过以下方式填充该属性:

  • 启用延迟加载:
    • public virtual Allocation Allocation { get; set; }
  • 急切加载: