簡體   English   中英

Ef Core 3.1 值轉換器

[英]Ef Core 3.1 value convertor

我有以下代碼,它使用 ef 3.1 核心值轉換,我收到以下錯誤,知道嗎?

實體類型“地址”需要定義主鍵。 如果您打算使用無密鑰實體類型,請調用“HasNoKey()”。

 public class Person {
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }

    [Required]
    public DateTime DateOfBirth { get; set; }

    public IList<Address> Addresses { get; set; }
  }

  

  public class Address {
    public string Type { get; set; }
    public string Company { get; set; }
    public string Number { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
  }

  public class PersonsConfiguration : IEntityTypeConfiguration<Person> {
    public void Configure(EntityTypeBuilder<Person> builder) {
      // This Converter will perform the conversion to and from Json to the desired type
      builder.Property(e => e.Addresses).HasConversion(
          v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
          v => JsonConvert.DeserializeObject<IList<Address>>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
    }
  }

您的地址 class 需要密鑰。 嘗試添加:

 [Key]
  public int AddressKey { get; set; }

到您的地址 class。

顯然,在 EntityTypeConfiguration 中注冊值轉換不起作用。 一旦我在 DbContext OnModelCreating 方法中注冊它 - 它就開始工作了。

 protected override void OnModelCreating(ModelBuilder modelBuilder) {
  modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetAssembly(this.GetType()));
  modelBuilder.Entity<Person>()
   .Property(p => p.Address)
   .HasConversion(new JsonValueConverter<Address>());

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM