Reputation: 2029
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?
Upvotes: 4
Views: 3194
Reputation: 2029
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,
Upvotes: 5