簡體   English   中英

實體框架代碼首先使用導航屬性一鍵

[英]Entity framework code first using navigation properties a Key

我在我的實體框架Code First上下文中有以下類

public class DataBinding
{
    [Key]
    public DataSource Source
    { get; set; }

    [Key]
    public DataType Type
    { get; set; }
    .....
}

DataSourceDataType都是同一個上下文的一部分,但是當我嘗試創建數據庫時,我得到以下錯誤: EntityType 'DataBinding' has no key defined. Define the key for this EntityType. DataBindings: EntityType: EntitySet 'DataBindings' is based on type 'DataBinding' that has no keys defined. EntityType 'DataBinding' has no key defined. Define the key for this EntityType. DataBindings: EntityType: EntitySet 'DataBindings' is based on type 'DataBinding' that has no keys defined. 我已經定義了兩個鍵為什么我會收到此錯誤?

問題是您使用兩種復雜類型作為PK,這是不允許的。 Key成員可以只是實體中的標量屬性。 復雜類型表示為不支持的復雜屬性。 選中此討論這個職位

要解決您的問題,您可以執行以下操作:

public class DataSource
{
    public int Id { get; set; }
    //...
}

public class DataType
{
    public int Id { get; set; }
    //...
}
public class DataBinding
{
    [Key,ForeignKey("Source"),Column(Order = 0)]
    public int DataSourceId {get;set;}
    [Key,ForeignKey("Type"),Column(Order = 1)]
    public int DataTypeId {get;set;}

   public DataSource Source { get; set; }

   public DataType Type { get; set; }
   //...
}

總改寫:

如果我理解得很好,您希望在同一上下文中的其他實體上實現具有基於外鍵的復合鍵的實體。 您無法直接鏈接實體,但可以按照示例鏈接此實體的主鍵。

來自外鍵的復合鍵

在這種情況下,您必須明確地寫出要在類中引入的(簡單類型)中的外鍵實體的主鍵,如前面的示例中所示,然后添加navigation屬性。

在構建復合鍵(無論如何)時,必須對鍵進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM