【发布时间】:2021-07-24 20:38:44
【问题描述】:
我想使用 Owned Types 制作 TableSplitting。我有以下型号:
public class Account
{
public GUID Id { get; set; }
public string Email { get; set; }
public StreetAddress Address { get; set; }
}
public class StreetAddress
{
public string Name { get; set; }
public string Address { get; set; }
public string Zipcode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public Location Location { get; set; }
}
public class Location
{
public double Lat { get; set; }
public double Lng { get; set; }
}
我这样定义了我的帐户映射:
public override void Map(EntityTypeBuilder<Account> map)
{
// Keys
map.HasKey(x => x.Id);
// Indexs
map.HasIndex(x => x.Email).IsUnique();
// Property mappings.
map.Property(x => x.Email).HasMaxLength(255).IsRequired();
// Owned types.
map.OwnsOne(x => x.Address, cb => cb.OwnsOne(a => a.Location));
}
当我运行迁移时,一切正常,并且在数据库中创建了列。但是当我尝试插入并保存这样的地址时:
var account1 = new Account("e@mail.com", "First", "Last")
{
Address = new StreetAddress()
{
Address1 = "Street 1",
City = "City",
Zipcode = "2000",
Country = "Denmark",
Location = new Location()
{
Lat = 0.0,
Lng = 5.5
}
}
};
this.Context.Accounts.Add(account1);
我收到此错误
消息“'Account' 的实体与表 'Accounts' 共享 'Account.Address#StreetAddress',但没有这种类型的实体 具有相同的键值 'Id:b7662057-44c2-4f3f-2cf0-08d504db1849' 已被标记为“已添加”。”
【问题讨论】:
-
它对我有用。你确定你调用了
Map显示的方法吗?因为只有当我不调用它时,我才会收到有问题的错误。 -
@Edit :根据文档,它应该按照约定添加。并且应该不需要主键,因为字段都应该进入已定义主键的 Account 表中 - 还是我弄错了?
-
@IvanStoev -> 我很确定 - 但我会检查一下以确认。
-
OwnedType 不支持与所有者在同一个表中映射的可选(即可为空)拥有类型(即使用表拆分)。我建议你看这个帖子github.com/aspnet/EntityFramework.Docs/issues/466
-
查看此文档:Owned Entity Types
标签: c# .net-core entity-framework-core