[英]load field from foreign-key related table as a native type
假設我有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; }
}
類型將是CustomerType中的Type屬性。 我在EF5中使用代碼優先。 當前不起作用,我一直在獲取The navigation property X is not a declared property on type..
異常The navigation property X is not a declared property on type..
。
您無法將屬性映射到單獨的表。 只有實體可以映射到表。 解決方法是,可以創建類型為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; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.