【问题标题】:EF4 CTP5 one to one mapping with existing databaseEF4 CTP5 与现有数据库的一对一映射
【发布时间】:2011-03-20 22:48:29
【问题描述】:

所以我有一个现有的数据库,其中包含一个用户表和一个机场表,每个表都有一个主键名称 ID。 Users 表有一个可为空的列 DefaultAirportID,它是 Airports 表 ID 的一个 fk。

这是我的 POCO:

public class User : IEntity
{
    [Key]
    [Required]
    public int ID { get; set; }

    public int? DefaultAirportID { get; set; }        
    public Airport DefaultAirport { get; set; }

    ...
}

public class Airport : IEntity
{
    [Key]
    [Required]
    public int ID { get; set; }

    ...
}

我不断收到错误消息“列名 'AirportID' 无效。”。我需要做什么才能让它填充 DefaultAirport 对象?

【问题讨论】:

    标签: entity-framework entity-framework-4 entity-framework-ctp5


    【解决方案1】:

    您需要使用 fluent API 来配置您的关联:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
                    .HasOptional(x => x.DefaultAirport)
                    .WithMany()
                    .HasForeignKey(n => n.DefaultAirportID);        
    }
    

    【讨论】:

    • Morteza,感谢您的快速回复。这让我更进一步。现在我不再遇到该异常,并且 DefaultAirportID 已正确填充,但 DefaultAirport 为空。
    • 没问题,如果你想让它延迟加载,那么你需要将它标记为virtual。否则,只需使用 Include 方法急切地加载它。
    • 莫特萨,非常感谢。您可能为我节省了大量研究时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多