简体   繁体   中英

zero-to-many relationship efcore

I have created two classes language and country using the format:

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

I have created the context and the database, but I noticed that the language table shows its columns as:

Id

LanguageName

CountryId

which indicates a one-to-many relationship, but this isn't what I want(countryId shouldn't be in the Language table) Is it possible to have a "zero-to-many" relationship in this format?

I order EF could recognize many-to-many relations, add public virtual ICollection Countries {get; set;} property to Language class and it should be enough

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

I usually recommend to add the third table. But if you are using Net5+ it is optional.

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

Also, if you are using Net5+ you don't need to add any relations, Ef will do it for you. But if you are using older version let us know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM