Given this code first data model, how would i configure or implement a LocalizedName navigation property on the Product entity, that uses the LocalNameKeyproperty on a Product instance for one of the keys, and the _languageId from the context as the other key?
public class SampleDataContext : DbContext
{
int _languageId;
public SampleDataContext(int languageId)
{
_languageId = languageId;
}
public DbSet<LocalizedName> LocalNames { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Language> Languages { get; set; }
}
public class LocalizedName
{
[Key, Column(Order = 0)]
public Guid Key { get; set; }
[Key, Column(Order = 1)]
public int LanguageId { get; set; }
public string Name { get; set; }
}
public class Language
{
public int Id { get; set; }
public string Name{ get; set; }
}
public class Product
{
public int Id { get; set; }
public string Sku { get; set; }
public Guid LocalNameKey { get; set; }
}
No you can’t. If you try, EF will try to create a table corresponding with the context and probably choke trying.
You’ll have to use a repository pattern to make sure that queries on any localized entity also incorporate a language id (which would be encapsulated in the repository, not the context).
As an aside, having FK’s to localized entries for each individual property of an entity can be very demanding performance-wise. See this Q&A for some good tips (not only the accepted answer).