我有一个描述组织的实体,包括其邮政地址。Address存储在属性(PostalAddress
)中,Organization的所有属性存储在同一个数据库表中。配置编译和迁移应用没有任何问题——如果我没有播种数据的话。我已经在Razor Pages中测试了标准CRUD -没有问题。
在OnModelCreating
中添加种子时,编译时出现错误。
实体类型"Organization"的种子实体。PostalAddress#PostalAddress'无法添加,因为没有为所需的属性'OrganizationId'提供值。
消息使我困惑,因为Organization
和PostalAddress
都没有OrganizationId
属性。数据库中也不存在影子属性。知道是什么导致了这个问题吗?
public abstract class BaseEntity<TEntity>
{
[Key] public virtual TEntity Id { get; set; }
}
public class MyOrganization : BaseEntity<long>
{
public string Name { get; set; } // Name of the Organization
public PostalAddress PostalAddress { get; set; } // Postal address of the Organization
public string Email { get; set; } // Email of the Organization
}
public class PostalAddress
{
public string StreetAddress1 { get; set; } // Address line 1
public string ZipCode_City { get; set; } // Zip code
public string Country { get; set; } // Country
}
public void Configure(EntityTypeBuilder<Organization> builder)
{
builder
.ToTable("Organizations")
.HasKey(k => k.Id);
// Configure PostalAddress owned entity
builder
.OwnsOne(p => p.PostalAddress, postaladdress =>
{
postaladdress
.Property(p => p.StreetAddress1)
.HasColumnName("StreetAddress1")
.HasColumnType("nvarchar(max)")
.IsRequired(false);
postaladdress
.Property(p => p.ZipCode_City)
.HasColumnName("ZipCode_City")
.HasColumnType("nvarchar(max)")
.IsRequired(false);
postaladdress
.Property(p => p.Country)
.HasColumnName("Country")
.HasColumnType("nvarchar(max)")
.IsRequired(false);
});
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder
.AddDBConfigurations();
// Seed data
builder
.Entity<Organization>(b =>
{
b.HasData(new Organization
{
Id = 1,
Name = "Test Organization",
Email = "nobody@nowhere.com"
});
b.OwnsOne(e => e.PostalAddress)
.HasData(new
{
StreetAddress1 = "1600 Pennsylvania Avenue NW", ZipCode_City = "Washington, D.C. 20500", Country = "USA"
});
});
}
异常消息令人费解,但很有帮助。当你将OrganizationId
添加到PostalAddress
的播种代码中,它就可以工作了。
modelBuilder
.Entity<Organization>(b =>
{
b.HasData(new Organization
{
Id = 1, // Here int is OK.
Name = "Test Organization",
Email = "nobody@nowhere.com"
});
b.OwnsOne(e => e.PostalAddress)
.HasData(new
{
OrganizationId = 1L, // OrganizationId, not Id, and the type must match.
StreetAddress1 = "1600 Pennsylvania Avenue NW",
ZipCode_City = "Washington, D.C. 20500",
Country = "USA"
});
});
这里可能涉及到一些未记录的约定。这是有道理的:拥有的类型可以添加到更多的实体类中,EF需要知道它是哪一个。有人会认为Id
应该足够了,毕竟,该类型已明确添加到b
,即Organization
。我认为一些内部代码泄漏到这里的公共API中,有一天这个故障可能会被修复。
请注意,所有者Id的类型必须完全匹配,而类型本身的播种接受具有隐式转换的值。
这是由惯例引起的,如果您需要建立一对一的关系,则需要在播种数据时添加MyOrganization的虚拟属性并在邮政地址对象中添加organizationId,这也有助于您配置一对一的关系https://www.learnentityframeworkcore.com/configuration/one-to-one-relationship-configuration