Efcore: EF Core Not Generating Fields for Owned Entity

Created on 16 Oct 2017  路  1Comment  路  Source: dotnet/efcore

Using EF Core 2.0, and I have a DateTimeSpan class with properties for Start and End. I'm using the type on two different properties in another entity. I configured that entity to use .OwnsOne() for both DateTimeSpan properties.

When I add migration, EF doesn't create fields for the owned entity properties.

```C#
public class DateTimeSpan
{
private DateTimeSpan()
{
}

private DateTimeSpan(DateTime start, DateTime end)
{
    Start = start;
    End = end;
}

public DateTime Start { get; }
public DateTime End { get; }

public TimeSpan TimeSpan => End - Start;

public static DateTimeSpan Create(DateTime start, DateTime end)
{
    return new DateTimeSpan(start, end);
}

}

public class OtherEntity
{
public DateTimeSpan PickupWindow { get; set; }
public DateTimeSpan DeliveryWindow { get; set; }
}

modelBuilder.Entity(builder =>
{
builder.OwnsOne(e=> e.PickupWindow);
builder.OwnsOne(e=> e.DeliveryWindow);
});
```

The resulting table does not have properties for PickupWindow.Start/End or DeliveryWindow.Start/End.

closed-question

Most helpful comment

@footedr Read-only properties are not mapped by convention, so Start and End will not be mapped. Also, the compiler-generated backing field in this case is read-only. So to map these, either:

  • Add private setters
    ```C#
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }
* Or declare an explicit backing field and then map the properties explicitly
```C#
private DateTime _start;
private DateTime _end;
public DateTime Start => _start;
public DateTime End => _end;

builder.OwnsOne(e => e.PickupWindow, b =>
{
    b.Property(e => e.Start);
    b.Property(e => e.End);
});

builder.OwnsOne(e => e.DeliveryWindow, b =>
{
    b.Property(e => e.Start);
    b.Property(e => e.End);
});

>All comments

@footedr Read-only properties are not mapped by convention, so Start and End will not be mapped. Also, the compiler-generated backing field in this case is read-only. So to map these, either:

  • Add private setters
    ```C#
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }
* Or declare an explicit backing field and then map the properties explicitly
```C#
private DateTime _start;
private DateTime _end;
public DateTime Start => _start;
public DateTime End => _end;

builder.OwnsOne(e => e.PickupWindow, b =>
{
    b.Property(e => e.Start);
    b.Property(e => e.End);
});

builder.OwnsOne(e => e.DeliveryWindow, b =>
{
    b.Property(e => e.Start);
    b.Property(e => e.End);
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

econner20 picture econner20  路  97Comments

JocaPC picture JocaPC  路  77Comments

divega picture divega  路  146Comments

obelixA picture obelixA  路  105Comments

0xdeafcafe picture 0xdeafcafe  路  189Comments