簡體   English   中英

在實體框架中是否可以將常量字符串作為外鍵

[英]Is it possible in entity framework to have a constant string as a foreign key

我希望連接在 id(真實列)和注釋類型(字符串)上。 以下示例不起作用,但應表明我的意圖。

public class Something
{
    [Key]
    [Column(Order=1)]
    public long Id { get; set; }

    [Key]
    [Column(Order = 2)]
    // Does this have to be in the database?
    public string CommentType = "Something-type-comment";

    [ForeignKey("CommentRecordId,CommentType")]
    public Comment Comment { get; set; }
}

public class Comment
{
    [Key]
    [Column(Order=1)]
    public long CommentRecordId { get; set; }

    [Key]
    [Column(Order=2)]
    public string CommentType { get; set; }   
}

當它轉換為 sql 時,我希望將其轉換為如下所示的內容。

SELECT * from Something s 
    JOIN Comment c ON 
        s.Id = c.CommentRecordId 
            and
        c.CommentType = 'Something-type-comment'; --there is no corresponding field in Something table

編輯:順便說一下,當我以這種方式嘗試時,我收到以下錯誤。 “關系約束中的從屬角色和主要角色中的屬性數量必須相同。”

我不相信有一種方法可以做你想做的使它的外鍵。 SQL 中沒有允許常量值成為外鍵一部分的構造。 您可以使用其他構造,如計算列、CHECK 約束或觸發器來確保基礎數據數據是“常量”,但外鍵必須引用表列。 但是,這些方法不能首先使用我知道的代碼進行配置,因此您必須在數據庫級別配置這些方法。

如果您必須有一個外鍵,那么我建議將該列保留在數據庫中並使其成為真正的外鍵,可能使用業務規則或上述方法之一。

第二種選擇是刪除外鍵屬性,並通過業務規則強制執行關系(和常量值)。 (即在您的存儲庫查詢中嵌入常量值,以便生成您指定的等效 SQL)。

就像是

var query = from s in Something
            join c in Comment
            on new {s.Id, CommentType = "Something-type-comment"} equals 
               new {c.CommentRecordId, c.CommentType}
            select new {s, c}

或者

var query = from s in Something
            join c in Comment
            on s.Id equals c.CommentRecordId
            where c.CommentType == "Something-type-comment" 
            select new {s, c}

暫無
暫無

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

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