Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decomposing structs in EF Core?

Say I have the following class:

struct Vector
{
    public float X { get; set; }
    public float Y { get; set; }
    public float Z { get; set; }
}

class Player
{
    public string Name { get; set; }
    public Vector Position { get; set; }
}

How do I configure that in Entity Framework (core) such that it maps to Name, PositionX, PositionY, PositionZ?

This is for code generation purposes, so I don't want the user having to create their POCO's with EF in mind (it emits to a whole lot of other languages too!)

like image 530
George R Avatar asked Jul 30 '18 19:07

George R


Video Answer


2 Answers

Currently (EF Core 3) it is not supported. However, there is a GitHub issue about it and looks like structs-as-owned-types has been accepted for future versions:

https://github.com/dotnet/efcore/issues/9906

like image 144
Xymanek Avatar answered Oct 03 '22 22:10

Xymanek


Was looking for the same thing, and came across this question. Thought I'd post what I found: The EF Core team suggest to store it as JSON in your database and use a custom value convertor:

modelBuilder.Entity<Order>()
    .Property(e => e.Vector)
    .HasConversion(
        v => JsonSerializer.Serialize(v, null),
        v => JsonSerializer.Deserialize<Vector>(v, null));

Not ideal though.

like image 22
brijber Avatar answered Oct 03 '22 22:10

brijber