0

I'm using Entity Framework Core 5.0.0 with SQLite3 (Entity Framework 6.4.4 is also installed) on .NET Core application, and have these 2 tables:

CREATE TABLE string 
(
    id     INTEGER NOT NULL,
    locale TEXT    NOT NULL,
    text   TEXT    NOT NULL,
    CONSTRAINT PK_string PRIMARY KEY (id, locale)
);

CREATE TABLE elem 
(
    id      INTEGER NOT NULL PRIMARY KEY,
    name    TEXT    NOT NULL,
    titleId INTEGER NOT NULL,
    briefId INTEGER NOT NULL
);

This scheme is correct and works, but in the context of the Entity Framework, this does not fully implement the convenience of EF: in the elem table, as a result, I only have an integer field, and not a List<string>.

On the one hand, I have a many-to-many relationship here, but incorrect many-to-many because there is no intermediate table. This is also no one-to-many because string does not have any relations to elem (because of not only elem is referencing to string).

Even many-to-many here will not be the most convenient, since I will have to create several intermediate tables...

I want to have a List<string> in the class, not just an integer field.

Is there any way to do it in EF without changing the schema (or with minimal changes, not like change to complete many-to-many relationship)?

1
  • As it turned out, EFC does not allow you to create such reference without changing the schema. Sample solution code with adding a table from the answer: repository.
    – Alex A.
    Nov 25, 2020 at 21:45

2 Answers 2

1

The presented database model lacks one important (from relational standpoint) part - the unique principal entity representing the one side of the many-to-one relationships for string.id, elem.titleId, elem.BriefId and similar.

Without that part the database model cannot use/enforce foreign key relationships, and these are essential for "convenient" EF relationship mapping.

So the minimal required modification is to introduce that entity/table, let call it for instance stringTable:

CREATE TABLE stringTable 
(
    id      INTEGER NOT NULL PRIMARY KEY
);

For existing database it should be populated with distinct id values from string table.

Now you can introduce FK relationships:

CREATE TABLE string 
(
    id     INTEGER NOT NULL CONSTRAINT FOREIGN KEY REFERENCES stringTable(id) ON DELETE CASCADE,
    locale TEXT    NOT NULL,
    text   TEXT    NOT NULL,
    CONSTRAINT PK_string PRIMARY KEY (id, locale)
);

CREATE TABLE elem 
(
    id      INTEGER NOT NULL PRIMARY KEY,
    name    TEXT    NOT NULL,
    titleId INTEGER NOT NULL CONSTRAINT FOREIGN KEY REFERENCES stringTable(id),
    briefId INTEGER NOT NULL CONSTRAINT FOREIGN KEY REFERENCES stringTable(id)
);

The corresponding EF entity model would be something like this (entity type and property names are arbitrary):

[Table("stringTable")]
public class StringTable
{
    [Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    // Navigation properties
    public virtual ICollection<StringEntry> Entries { get; set; }
}

[Table("string")]
public class StringEntry
{
    [Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Column("locale"), Required]
    public string Locale { get; set; }
    [Column("text"), Required]
    public string Text { get; set; }
    // Navigation properties
    public virtual StringTable Table { get; set; }
}

[Table("elem")]
public class Element
{
    [Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Column("name"), Required]
    public string Name { get; set; }
    [Column("titleId")]
    public int TitleId { get; set; }
    [Column("briefId")]
    public int BriefId { get; set; }
    // Navigation properties
    public virtual StringTable Title { get; set; }
    public virtual StringTable Brief { get; set; }
}

with composite PK and relationships mappings:

modelBuilder.Entity<StringEntry>()
    .HasKey(e => new { e.Id, e.Locale });

modelBuilder.Entity<StringEntry>()
    .HasRequired(e => e.Table)
    .WithMany(e => e.Entries)
    .HasForeignKey(e => e.Id)
    .WillCascadeOnDelete();

modelBuilder.Entity<Element>()
    .HasRequired(e => e.Title)
    .WithMany()
    .HasForeignKey(e => e.TitleId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Element>()
    .HasRequired(e => e.Brief)
    .WithMany()
    .HasForeignKey(e => e.BriefId)
    .WillCascadeOnDelete(false);

With all that being in place, you can access the associated strings with Element elem as follows:

elem.Title.Entries
elem.Brief.Entries

project/extract the associated texts as follows:

TitleTexts = elem.Title.Entries.Select(e => e.Text)
BriefTexts = elem.Brief.Entries.Select(e => e.Text)

project/extract the text for a specific string locale:

TitleText = elem.Title.Entries.Where(e => e.Locale == locale).Select(e => e.Text).FirstOrDefault()
BriefText = elem.Brief.Entries.Where(e => e.Locale == locale).Select(e => e.Text).FirstOrDefault()

etc.

Update: For EF Core, the entity model/data annotations needed are exactly the same as above, just the fluent configuration must use the EF Core equivalents (all these go to OnModelCreating method override of your DbContext derived class):

modelBuilder.Entity<StringEntry>()
    .HasKey(e => new { e.Id, e.Locale });

modelBuilder.Entity<StringEntry>()
    .HasOne(e => e.Table)
    .WithMany(e => e.Entries)
    .HasForeignKey(e => e.Id)
    .OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Element>()
    .HasOne(e => e.Title)
    .WithMany()
    .HasForeignKey(e => e.TitleId)
    .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<Element>()
    .HasOne(e => e.Brief)
    .WithMany()
    .HasForeignKey(e => e.BriefId)
    .OnDelete(DeleteBehavior.Restrict);
13
  • I tried using EF 6.2 (which, as it says in the docs.microsoft, HasRequired), but I couldn't use it and replaced it with hasone. I'm currently using EF 6.4.4. It should be noted that EF can't leave alone StringTable and requires HasNoKey. But all the previous ones would not have mattered if the concept had worked. But I have an error: System.InvalidOperationException: 'Unable to determine the relationship represented by navigation 'Element.Brief' of type 'StringTable'. Either manually configure the relationship, or ignore ...' (I wrote the code only for brief).
    – Alex A.
    Nov 18, 2020 at 23:12
  • The answer is for EF6 ("I'm using Entity Framework 6..."), while the methods you've mentioned (HasOne, HasNoKey etc.) are fluent APIs for EF Core which is completely different system. The solution is tested and works, the database design is as specified in the answer, for EF Core you neeed to replace the fluent configuration with the corresponding EF Core methods. And standalone StringTable is a must and is supported in both EFs. The whole purpose of that entity/table is to hold the key, so EFC keyless entity (HasNoKey) is not an option, you are doing something wrong.
    – Ivan Stoev
    Nov 19, 2020 at 3:01
  • yes, I'm using EFC5 AND EF6 (on .net core app). EFC is need like provider for local sqlite. Standalone EF can't work with sqlite. I used EF to extend the capabilities of EFC. For example, EF allowed the use of [Index ("index_name")]. I assumed that when adding EF, its functions would complement EFC. I was probably wrong about that.
    – Alex A.
    Nov 19, 2020 at 16:42
  • Can you extend the answer with a specific case of "EFC5 + EF6 on .NET Core 5"?
    – Alex A.
    Nov 19, 2020 at 16:51
  • Sure I can extend it with EFC fluent configuration. What about EFC + EF6, I have no idea what "+" means - classes, migrations, conventions, many fluent APIs are completely different. You should choose one or another.
    – Ivan Stoev
    Nov 19, 2020 at 17:21
0

Unless the "string" table has an ElementId to point back to an element, Element would not contain a list of "string" entities.

From the looks of your schema, I'd take a stab that your titleId and possible briefId are FK references to the "string" table for localized title and brief text? (using "string" as a table/entity name is going to lead to lots of confusion)

If so, you would have something like:

[Table("elem")]
public class Element
{
    // ...
    public int TitleId {get; set;}
    [ForeignKey("TitleId")]
    public virtual StringEntity Title { get; set; } 

    public int BriefId {get; set;}
    [ForeignKey("BriefId")]
    public virtual StringEntity Brief { get; set; } 
}

[Table("string")]
public class StringEntity
{ // ...
}

Then to get the localized resource for title: element.Title.Text

Update: Ok, the string resource table uses a composite key for the ID plus the locale. Since your joining table does not have a locale ID then EF cannot directly map these two elements. You can query information across these tables via Joins and projection into view models however...

[Table("string")]
public class StringEntry
{
    [Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Column("locale"), Required]
    public string Locale { get; set; }
    [Column("text"), Required]
    public string Text { get; set; }
    // Navigation properties
    public virtual StringTable Table { get; set; }
}

[Table("elem")]
public class Element
{
    [Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Column("name"), Required]
    public string Name { get; set; }
    [Column("titleId")]
    public int TitleId { get; set; }
    [Column("briefId")]
    public int BriefId { get; set; }
}

given a view model like:

[Serializable]
public class ElementViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Brief { get; set; }
}

To query the localized data...

int localeId = GetCurrentLocaleId(); // Some method/code to get the current locale.

var elements = context.Elements
    .Join(context.Strings, 
        x => new { Id = x.TitleId, Locale = localeId }, 
        x => new { x.Id, x.LocaleId }, 
        (e, s) => new { Element = e, Title = s })
    .Join(context.Strings, 
        x => new { Id = x.Element.BriefId, LocaleId = localeId }, 
        x => new { x.Id, x.LocaleId }, 
        (e, s) => new { Element = e.Element, Title = e.Title, Brief = s })
    .Select(x => new ElementViewModel
    { 
        Id = x.Element.Id, 
        Name = x.Element.Name,
        Title = x.Title.Text,
        Brief = x.Brief.Text 
    }).ToList();

Needless to say, if you're using a lot of localized strings like this, the queries are going to get rather complicated and cumbersome.

3
  • "using "string" isn't a best idea" - I khow. This is not a real table name in the database - I shortened the names for the question.
    – Alex A.
    Nov 18, 2020 at 19:51
  • With the configuration you suggested, I get the following error: System.InvalidOperationException: 'The relationship from 'Element.Brief' to 'StringEntity' with foreign key properties {'BriefId' : ulong} cannot target the primary key {'id' : ulong, 'locale' : string} because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.' This is all because of the composite primary key. The peculiarity of working with it is the reason for my question.
    – Alex A.
    Nov 18, 2020 at 22:29
  • I've updated my answer to demonstrate an option for handling the composite keys on the string. Ultimately EF cannot map this relationship. It'd be nice if you could map a FK using .HasForeignKey(x => new { Id = x.TitleId, LocaleId = localeId }) however this doesn't work. EF is expecting to use the key expression for column joins and doesn't support a constant value like you might get away with in raw SQL.
    – Steve Py
    Nov 19, 2020 at 3:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.