Ken*_*gan 9 c# entity-framework-core ef-core-3.0
我有一个主实体 Profile,它的属性 Name 是一个值对象。Name 对象有两个属性 First 和 Last。当我使用 Fluent API 将 Name 对象属性映射到 Profile 表中的列时,我指定它们是必需的。当我创建迁移时,它说可空为真。我认为这与以下事实有关,即在 EF Core 3.0 中拥有的实体现在是可选的,但我如何告诉 EF 它们实际上是必需的?
public class Profile
{
public Name Name { get; private set; }
...
}
Run Code Online (Sandbox Code Playgroud)
public class Name
{
public string First { get; }
public string Last { get; }
...
}
Run Code Online (Sandbox Code Playgroud)
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();
});
}
Run Code Online (Sandbox Code Playgroud)
您能提供的任何帮助都会很棒。
除了在 中设置.IsRequired()所需的属性外ValueObject,您还需要在 之后根据需要配置导航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();
=============^========================================^
Run Code Online (Sandbox Code Playgroud)
问题: https : //github.com/dotnet/efcore/issues/12100
致谢: @AndriySvyryd
| 归档时间: |
|
| 查看次数: |
1666 次 |
| 最近记录: |