【问题标题】:How to make an OwnsOne property in EF Core 3.0 required when mapping to SQL Server columns?映射到 SQL Server 列时,如何在 EF Core 3.0 中设置 OwnsOne 属性?
【发布时间】:2019-10-16 15:55:02
【问题描述】:

我有一个主实体 Profile,它的属性 Name 是一个值对象。 Name 对象有两个属性 First 和 Last。当我使用 Fluent API 将 Name objects 属性映射到 Profile 表中的列时,我指定它们是必需的。当我创建迁移时,它说 nullable 是真的。我认为这与在 EF Core 3.0 中拥有的实体现在是可选的这一事实有关,但我如何告诉 EF 它们实际上是必需的?

public class Profile
{
   public Name Name { get; private set; }
   ...
}
public class Name
{
   public string First { get; }
   public string Last { get; }
   ...
}
public override void Configure(EntityTypeBuilder<Profile> builder)
{
   base.Configure(builder);

   builder.OwnsOne(
                navigationExpression: p => p.Name,
                buildAction: n =>
                {
                    n.Property(n => n.First)
                        .HasColumnName("NameFirst")
                        .HasMaxLength(25)
                        .IsRequired();

                    n.Property(n => n.Last)
                        .HasColumnName("NameLast")
                        .HasMaxLength(25)
                        .IsRequired();
                });
}

您能提供的任何帮助都会很棒。

【问题讨论】:

    标签: c# entity-framework-core ef-core-3.0


    【解决方案1】:

    EF 核心 5

    除了在ValueObject 内的所需属性上设置.IsRequired()x.OwnsOne(...)之后需要根据需要配置导航:

    builder.OwnsOne(o => o.Address, a =>
                {
                    a.WithOwner();
    
                    a.Property(p => p.Street)                    
                        .IsRequired();
    
                    a.Property(p => p.ZipCode)
                        .IsRequired();
    
                    a.Property(p => p.City)
                        .IsRequired();
    
                }).Navigation(p => p.Address).IsRequired();
     =============^========================================^
    
    

    问题: https://github.com/dotnet/efcore/issues/12100

    致谢: @AndriySvyryd

    【讨论】:

      【解决方案2】:

      我联系了 EF Core 团队,目前唯一的方法是手动更改创建的迁移以设置 nullable = false。它已被标记为功能请求,所以我们希望有一天他们能修复它!

      【讨论】:

      • 如果您使用.EnsureCreated,则不会应用迁移,因此属性是可为空的。我认为 MS 必须 解决这个问题,否则不允许在 own 配置中使用 .IsRequired 方法。无论如何,感谢您报告此事。
      • 链接到上述功能请求:github.com/dotnet/efcore/issues/18445
      猜你喜欢
      • 2018-03-06
      • 2023-02-10
      • 2018-08-28
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      相关资源
      最近更新 更多