零对多关系 efcore

时间:2021-07-24 17:25:16

标签: c# entity-framework asp.net-web-api .net-core entity-framework-core

我使用以下格式创建了两个类语言和国家:

public class Country{
public string Id{get; set;}
public string CountryName {get; set;}
public ICollection<Language> Languages {get; set;}
}
public class Language{
public string Id{get; set;}
public string LanguageName{get; set;}
}

我已经创建了上下文和数据库,但我注意到语言表将其列显示为:

身份证

语言名称

国家编号

表示一对多关系,但这不是我想要的(countryId 不应在 Language 表中) 这种格式是否可以有“零对多”的关系?

1 个答案:

答案 0 :(得分:1)

我命令 EF 可以识别多对多关系,添加公共虚拟 ICollection 国家 {get;将;} 属性设置为 Language 类,应该足够了

public class Country
{
public string Id{get; set;}
public string CountryName {get; set;}
public virtual ICollection<Language> Languages {get; set;}
public virtual ICollection<CountryLanguage> CountryLanguages {get; set;}
}

public class Language
{
public string Id{get; set;}
public string LanguageName{get; set;}
public virtual ICollection<Country> Countries {get; set;}
public virtual ICollection<CountryLanguage> CountryLanguages {get; set;}
}

我通常建议添加第三个表。但如果您使用的是 Net5+,则它是可选的。

public class CountryLanguage
{
public string CountryId{get; set;}
public string LanguageId{get; set;}
public virtual Country Country {get; set;}
public virtual Language Language {get; set;}
}

此外,如果您使用的是 Net5+,则无需添加任何关系,Ef 将为您完成。但如果您使用的是旧版本,请告知我们。

相关问题