How to map an owned property to a private field

c# ef-core-3.0 entity-framework-core

Question

I have a value object, so the getters but not the setters are present in its properties. I then have an entity with a private field and a public getter. Something along these lines:

public class Settings {
  private string _instance;
  private string _domain;

  public Settings(string instance, string domain) {
    _instance = instance;
    _domain = domain;
  }
  private Settings() {
    _instance = default!;
    _domain = default!;
  }

  public string Instance => _instance;
  public string Domain => _domain;
}

public class Tenant {
  private Guid _id;
  private string _name;
  private Settings _settings;

  public Tenant(string name) {
    _id = Guid.Empty;
    _name = name;
    _settings = new Settings("etc", "etc");
  }
  private Tenant() {
    _id = default;
    _name = default!;
    _settings = default!;
  }

  public Guid Id => _id;
  public string Name => _name;
  public Settings => _settings;

  protected void OnSettingsChanged() { 
    // do stuff like adding domain events and sending notifications 
  }
  public void ChangeSetting(Settings newSettings) {
    // do some model validation
    _settings = newSettings;
    OnSettingsChanged();
  }
}

I'm using Entity Framework Core 3 and C# 8 with.NET Core 3. Now, as I put into practiceIEntityTypeConfiguration<Tenant> I don't have any trouble setting, for example, Name since I can use HasField and give the name of the private field. But for Settings, that is ineffective. I use OwnsOne there, but the HasField attribute isn't accessible.

builder.Property(x => x.Name)
  .HasField("_name")
  .HasMaxLength(100);
builder.OwnsOne(x.Settings, y => {
  y.Property(z => z.Instance)
   .HasField("_instance")
   .IsRequired(true);
  y.Property(z => z.Domain)
   .HasField("_domain")
   .IsRequired(true);
  //y.HasField() ??
});

But I can't figure out how to instruct EF to map the Settings property to the private_settings variable. I attempted to add a call toProperty prior to the callOwnsOne :

...
builder.Property(x => x.Settings)
  .HasField("_settings");
builder.OwnsOne(x.Settings, y => {
  y.Property(z => z.Instance)
   .HasField("_instance")
   .IsRequired(true);
  y.Property(z => z.Domain)
   .HasField("_domain")
   .IsRequired(true);
});

I suppose this occurs because I'm configuring the property Settings twice because I get an error when I try to add a migration: The property or navigation 'Settings' cannot be added to the entity type 'Tenant' because a property or navigation with the same name already exists on entity type 'Tenant'.

What is OwnsOne's HasField equivalent, and how may I go about doing this? I appreciate it.

1
1
11/7/2019 8:10:59 PM

Accepted Answer

ZZZ_tmp
1
11/7/2019 8:10:34 PM






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