簡體   English   中英

導航屬性的組合鍵

[英]Composite Key to navigation property

我正在嘗試創建一個表來保存有關特定實體的注釋。 我有一個稱為Notes的實體,我想存儲它所引用的實體的PK。 我想要一個包含鍵和包含主鍵的表名的組合鍵。 請參閱以下示例:

public class Lot
{
    public int LotId { get; set; }
    public virtual ICollection<Note> Notes { get; set; }
}
public class Task
{
    public int TaskId { get; set; }
    public virtual ICollection<Note> Notes { get; set; }
}

public class Note
{
    public int Id { get; set; }
    public int EntityReferenceId { get; set; }

    public string EntityType { get; set; }
    public string Comment {get; set; }
}

因此,在Notes表中將有:

Id:1 EntityReferenceId:1 EntityType:批注:“評論一,第一批”

ID:2 EntityReferenceId:1 EntityType:批注:“評論二,第一批”

ID:3 EntityReferenceId:1 EntityType:任務注釋:“注釋一,任務一”

似乎在數據庫中應該有這種可能,但是我對模型沒有任何運氣。 有人可以幫我指出正確的方向嗎?

使Note類抽象化,並創建兩個派生類,一個派生類,一個用於批注,另一個用於任務注釋,如下所示:

public abstract class Note
{
    public int Id { get; set; }

    public string Comment {get; set; }
}

public class NoteForLot : Note
{
    public int LotId { get; set; }
    public virtual Lot Lot { get; set; }
}

public class NoteForTask : Note
{
    public int TaskId { get; set; }
    public virtual Task Task { get; set; }
}

注意每個子類如何引用正確的父對象。

您的LotTask類需要更改以反映更改:

public class Lot
{
    public int LotId { get; set; }
    public virtual ICollection<NoteForLot> Notes { get; set; }

    public Lot()
    {
        Notes = new HashSet<NoteForLot>();
    }
}

public class Task
{
    public int TaskId { get; set; }
    public virtual ICollection<NoteForTask> Notes { get; set; }

    public Task()
    {
        Notes = new HashSet<NoteForTask>();
    }
}

Entity Framework將在注釋表中自動創建一列(以替換您的EntityType屬性)以區分兩種注釋。 該列在數據庫中將稱為Discriminator ”。

此功能稱為“每個層次表繼承”。 您可以在Google上搜索以獲得有關它的更多信息。

暫無
暫無

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

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