如何在映射到 SQL Server 列时使 EF Core 3.0 的 OwnsOne 属性成为必填项?

15

我有一个主实体“Profile”,它具有一个“名称”属性,该属性是一个值对象。名称对象有两个属性:名字和姓氏。当我使用Fluent API将名称对象的属性映射到Profile表中的列时,我指定它们是必需的。但是,在创建迁移时,它显示可空为true。我认为这与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();
                });
}

您能提供的任何帮助都将是极好的。

2个回答

18

EF Core 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


6

我联系过EF Core团队,目前唯一的方法是手动更改创建的迁移以设置nullable = false。这已被标记为功能请求,希望有一天他们能够解决这个问题!


1
如果您使用.EnsureCreated,则迁移不会应用,因此属性是_nullable_。我认为MS 必须解决这个问题,否则不要允许在_own_配置内使用.IsRequired方法。无论如何,感谢您报告此问题。 - Max
以上功能请求的链接:https://github.com/dotnet/efcore/issues/18445 - foka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接