【问题标题】:Entitiy framework one-to-many mapping with condition实体框架与条件的一对多映射
【发布时间】:2014-08-09 13:05:24
【问题描述】:

我的 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”中存在差异?

【问题讨论】:

    标签: c# mysql entity-framework ef-code-first


    【解决方案1】:

    你可以像这样创建 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 进行复杂的映射,因为它提供了一些灵活性。你可以在这里查看:

    Fluent Api Example

    【讨论】:

      猜你喜欢
      • 2011-12-29
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多