首页 > 解决方案 > 零对多关系 efcore

问题描述

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

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;}
}

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

ID

语言名称

国家 ID

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

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

解决方案


我命令 EF 可以识别多对多关系,添加公共虚拟 ICollection 国家 {get; set;} 属性到语言类,应该足够了

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 会为您完成。但如果您使用的是旧版本,请告诉我们。


推荐阅读