0

假设我有 2 张桌子:

Customer
    Id int
    Name varchar
    TypeId int

CustomerType
    Id int
    Type varchar

TypeId 是 CustomerType 的 Id 的外键。现在如何使用 EF 将 Customer 加载为这样的实体:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int TypeId { get; set; }
    [ForeignKey("TypeId")]
    public string Type { get; set; }
}

Type 是 CustomerType 的 Type 属性。我在 EF5 中使用代码优先。它目前不起作用,我不断收到The navigation property X is not a declared property on type.. 异常。

4

1 回答 1

0

您不能将属性映射到单独的表。只有实体可以映射到表。作为解决方法,您可以创建属性,其类型CustomerType将映射到第二个表,并将Type属性标记为未映射:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int TypeId { get; set; }
    [ForeignKey("TypeId")]
    protected CustomerType CustomerType { get; set; }
    [NotMapped]
    public string Type 
    { 
        get { return CustomerType.Type; }
        set { CustomerType.Type = value; }
    }
}
于 2013-03-04T17:37:11.530 回答