Shadi Fayed
Shadi Fayed

Reputation: 397

EF Core navigation property without relations(foreign-key)

I have three classes

public class Country
{
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public byte CountryID { get; set; }
        public byte OfficialLangID { get; set; }
}

public class Language
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public byte LangID { get; set; }
}

public class Name
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public byte NameID { get; set; }
    public bool isLanguage { get; set; } // true for language - false for country
    public byte FK { get; set; } // FK=LangID or CountryID
}

Now I want to create Navigation properties:

I want to do it in this way for many reasons, one of them to search for all the names in one table without joining.

Please don't suggest another way,I want navigation properties for my way.

Upvotes: 0

Views: 148

Answers (1)

alim91
alim91

Reputation: 546

why you're doing it like this? putting a boolean field to check the type of the entity here doesn't make any sense? in the end, the ef framework will create 2 tables. here is my approach:

public class Country
{
        public byte Id {get;set;}
        public string Name {get;set;}

        public int LanguageId {get;set;}
}

public class Language
{
    public byte Id {get;set;}
    public string Name {get;set;}

    // assuming that each language may have one or many countries
    public ICollection<Country> Countries {get;set;}
}

ef core here will create the tables and the relations automatically. now if you see some code duplications (like I've understood), that the 2 entities use the same field types and names, here is what you can do

public abstract class EntityBase
{
        public byte Id {get;set;}
        public string Name {get;set;}
}

now inherit this abstract class to the entity class

public class Country : EntityBase
{
        public int LanguageId {get;set;}
}

public class Language : EntityBase
{
    public ICollection<Country> Countries {get;set;}
}

Upvotes: 2

Related Questions