【问题标题】:unconventional foreign key fields maps to NULL in EF6EF6 中非常规外键字段映射到 NULL
【发布时间】:2015-06-27 17:35:32
【问题描述】:

我正在使用 EF6。我有两个模型 PowerLine 和 PowerSource。 PowerSource 有一个指向 PowerLine 的外键列。问题是 PowerLine 对象正在填充 PowerSource 列表,但 PowerSource 的 SourcePowerLine 导航属性始终为 NULL。我的模型如下:

public class PowerLine
{
    [Key]
    public int ID { get; set; }                                    
    public virtual ICollection<PowerSource> PowerSources { get; set; }    
}

public class PowerSource
{
    [Key]
    public int ID { get; set; }    
    public int SourcePowerLineID {get;set;}

    [ForeignKey("SourcePowerLineID")]        
    public virtual PowerLine SourcePowerLine { get; set; }                                                         
 }

我也尝试了 Column(Order) 属性来设置正确的顺序,我也尝试使用 Fluent API,如下所示:

        modelBuilder.Entity<PowerSource>()
                    .HasRequired(c => c.SourcePowerLine )
                    .WithMany(b => b.PowerSources)
                    .HasForeignKey(c => c.SourcePowerLineID);

【问题讨论】:

  • 不确定我是否正确理解了您的问题,但您是否尝试过:context.PowerSources.Include("SourcePowerLine")

标签: c# entity-framework entity-framework-6


【解决方案1】:

您的[ForeingKey()] 属性并没有真正指向任何地方,请尝试:

[ForeignKey("PowerLine")]
public int SourcePowerLineID { get; set; }

【讨论】:

  • 您的解决方案给了我以下错误:Additional information: The ForeignKeyAttribute on property 'SourcePowerLineID' on type 'power.Model.PowerSource' is not valid. The navigation property 'PowerLine' was not found on the dependent type 'power.Model.PowerSource'. The Name value should be a valid navigation property name.
猜你喜欢
  • 1970-01-01
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多