Flatten complex object on entity in DB

c# entity-framework-core

Question

Suppose I have following objects:

Entity:

public class MyEntity : NamedEntity
{
}

public abstract class NamedEntity : VersionedEntity
{
    public LocalizedText Name { get; set; }
}

Complex object (LocalizedText):

public class LocalizedText : ILocalized<string>
{
    protected LocalizedText()
    {
    }

    public LocalizedText(string en, string de = null, string fr = null)
    {
        En = en;
        De = de;
        Fr = fr;
    }

    public string En { get; set; }
    public string De { get; set; }
    public string Fr { get; set; }
}

With this, I get following exception:

System.InvalidOperationException: 'The entity type 'LocalizedText' requires a primary key to be defined.'

I don't want to make an entity out of LocalizedText, but want it stored in the DB in columns of the MyEntity table, e.g. Name_EN, Name_DE and Name_FR.

How can I achieve this?

1
0
10/8/2018 12:13:40 PM

Popular Answer

I've found the solution here https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/#owned-entities-and-table-splitting

For the above code I've adapted my DbContext implementation with:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<MyEntity>()
               .OwnsOne(r => r.Name);
    }

Which results in following CREATE (irrelevant parts masked in [...]):

CREATE TABLE [dbo].[MyEntity](
    [...]
    [Name_En] [nvarchar](max) NULL,
    [Name_De] [nvarchar](max) NULL,
    [Name_Fr] [nvarchar](max) NULL,
0
10/8/2018 2:17:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow