EF两个一对多关系,出错了

时间:2015-07-18 05:38:34

标签: entity-framework

我想做什么:

我有一个名为'Department'的实体,每个部门可能有几种不同语言的翻译(例如英语为“Sales”,德语为“Sales”等)。

此外,每个“部门”都可以使用两种语言的同义词。

我希望尽可能灵活地提供大量可用的翻译和同义词,因为我不知道我将为每个部门提供多少翻译或同义词。

因此,我的想法是做这样的事情:

public class DepartmentEntity
{
    public Departments Id
    {
        get;
        set;
    }

    public List<DepartmentNaming> Names
    {
        get;
        set;
    }

    public List<DepartmentNaming> Synonyms
    {
        get;
        set;
    }
}


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

    public virtual DepartmentEntity Department { get; set; }

    public string Name
    {
        get;
        set;
    }

    public Language Language
    {
        get;
        set;
    }
}

这导致某种奇怪的表格,我有以下列:

[Id]                   INT            IDENTITY (1, 1) NOT NULL,
[Name]                 NVARCHAR (MAX) NULL,
[Language]             INT            NOT NULL,
[Department_Id]        INT            NULL,
[DepartmentEntity_Id]  INT            NULL,
[DepartmentEntity_Id1] INT            NULL,

基本上,我将此视为一对多关系,因为一个特定部门可以有多个翻译,一个特定翻译属于一个特定部门(同义词相同)。

那么 - 为什么它会为我创建DepartmentEntity_Id和DepartmentEntity_Id1?我错过了什么?可能我需要以某种方式告诉EF关于我想要实现的目标,但我不知道如何......

由于

1 个答案:

答案 0 :(得分:2)

正如我从您的问题和您的评论中所理解的,名称,同义词是DepartmentName的类型

无需在DepartmentEntity中引用DepartmentName。

下面是可能对您的实现有所帮助的设计,您可以按照与您匹配的方式重命名类

// this will hold the defualt department names
public class Department
{
    public int Id{get;set;}
    public string Name{get;set;}
}

// this will hold the translation type: name or synonym
public class TranslationType
{
    public int Id{get; set;}
    public string Name{get; set;}
}
// this will hold the translation language name: en,gr...
public class Language
{
    public int Id{get; set;}
    public string Name{get; set;}
}

// this will hold the translated name and its type as synonym or name
public class Translation
{
    public int Id{get; set;}
    public string Name{get; set;}
    public int LanguageId{get; set;}
    public int TranslationTypeId{get;set;}

    public Language Language{get; set;}
    public TranslationType TranslationType{get; set;}
}

// this will be many to many relation to link departments to its translated languages
public class DepartmentTranslation
{       
    public Department Department{get; set;}
    public Translation Translation{get; set;}
}

希望这会对你有所帮助