簡體   English   中英

實體框架與條件的一對多映射

[英]Entitiy framework one-to-many mapping with condition

我的DBMS(mysql)中具有以下結構:

create table tasks
(
    id int auto_increment not null,
        primary key (id),
    name varchar(200) not null,
        unique(name)    
);

create table species
(
    id int auto_increment not null,
        primary key (id),
    id_task int,
        foreign key (id_task) references tasks(id) on delete cascade,
    is_history tinyint not null default 0
);

一個任務可以具有當前種類(當is_history = 0時)和歷史種類(當is_history = 1時)。 我創建了以下類:

public class Specie
{
    public int Id { get; set; }
    public int TaskId { get; set; }
    public Task ParentTask { get; set; }
}

public class Task
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Specie> CurrentSpecies { get; set; }
    public ICollection<Specie> HistSpecies { get; set; }
}

用代碼優先創建映射以將“ CurrentSpecies”和“ HistSpecies”映射到一個表“ species”(在一個字段“ is_history”中具有差異)的正確方法是什么?

您可以像這樣創建Species類:

public class Specie
{
    public int Id { get; set; }

    public int TaskId { get; set; }

    public Task ParentTask { get; set; }

    public ICollection<Specie> CurrentSpecies { get; set; }

    public ICollection<Specie> HistSpecies { get; set; }
}

如果必須創建Task對象和該對象內的集合,那么我建議您重新考慮設計。 從本質上講,任務對象應該成為聚合根。

我還將考慮使用Fluent Api進行復雜的映射,因為它具有一定的靈活性。 您可以在這里查看:

流利的Api示例

暫無
暫無

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

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