c# - 零对多关系 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 表中)这种格式是否可以有“零对多”关系?
解决方案
我命令 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 会为您完成。但如果您使用的是旧版本,请告诉我们。
推荐阅读
- php - 如何在 laravel 中同时使用 select 函数和 with 函数
- firebase - 是否可以使用 Cloud Functions 在 Firestore 中获取 userID 或 currentUser 子集合?
- cassandra - 适用于 z/OS (USS) 的 JNA 库
- ffmpeg - 在 FFmpeg 中,-filter_complex 可以做 -filter 可以做的所有事情吗?(即,是否直接替换)
- c# - 自定义公式列表数据验证
- python - folium 地图中的非线性颜色图
- django - React 和 DRF:Cookie 不会自动保存
- rust-tokio - 如何将超响应正文写入文件?
- python - 如何使用 Selinium Python 在 td web-table 中获取文本
- powershell - Powershell - Outlook 高级搜索不通过组织框递归