如何在Entity Framework Core 2.0中映射值对象

Mar*_*ndl 3 c# entity-framework

考虑一个Customer具有Resource表示客户徽标的对象的实体:

public class Customer
{
    public Guid Id { get; set; }

    public string CompanyName { get; set; }

    public Resource Logo { get; set; }
}

public class Resource
{
    public string Uri { get; set; }

    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所尝试但是因为Logo是一个复杂的对象而得到错误:

var customer = modelBuilder.Entity<Customer>().ToTable("Customers");
customer.HasKey(c => c.Id);
customer.Property(c => c.CompanyName).HasColumnName("Company");
customer.Property(c => c.Logo);
Run Code Online (Sandbox Code Playgroud)

我怎么能存储与EF核心2.0资源作为一个值对象 的客户表?

Fed*_*uma 10

如果您想共享同一个表,您只需定义一个拥有的实体:

modelBuilder.Entity<Customer>().OwnsOne(c => c.Logo);
Run Code Online (Sandbox Code Playgroud)

按照惯例,它只使用一个表.

  • @FercoCQ 您需要在 `OwnsOne` 方法中定义这些属性:`modelBuilder.Entity&lt;Customer&gt;().OwnsOne(c =&gt; c.Logo, x =&gt; { x.Property(p =&gt; p.Logo).HasColumnName ("LogoColName"); });` (2认同)