.net c#从外键相关表中加载字段作为本机类型

load field from foreign-key related table as a native type
2021-12-04
  •  译文(汉语)
  •  原文(英语)

假设我有 2 个表:

Customer
    Id int
    Name varchar
    TypeId int

CustomerType
    Id int
    Type varchar

TypeId 是 CustomerType 的 Id 的外键.现在我如何使用 EF 将客户加载为这样的实体:

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.. 异常.

解决过程1

您不能将属性映射到单独的表.只有实体可以映射到表.作为解决方法,您可以创建属性,其类型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; }
    }
}

Say I have 2 Tables:

Customer
    Id int
    Name varchar
    TypeId int

CustomerType
    Id int
    Type varchar

TypeId is a foreign key to CustomerType's Id. Now how can I load the Customer as such an entity with EF:

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 would be the Type attribute from CustomerType. I am using code-first with EF5. It does currently not work, I keep getting the The navigation property X is not a declared property on type.. exception.

Solutions1

You can't map property to separate table. Only entities could be mapped to tables. As workaround you can create property, with type of CustomerType which will be mapped to second table, and mark Type property as not mapped:

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; }
    }
}
转载于:https://stackoverflow.com/questions/15207423/load-field-from-foreign-key-related-table-as-a-native-type

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入