Run*_*sen 15 c# entity-framework-core .net-core
我想使用自有类型进行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; }
}
Run Code Online (Sandbox Code Playgroud)
我定义了我的帐户映射,如下所示:
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));
}
Run Code Online (Sandbox Code Playgroud)
当我运行迁移时,事情正在发挥作用,并且在数据库中创建了列.但是当我尝试插入并保存这样的地址时:
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);
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
消息"'帐户'的实体正在与'Account.Address#StreetAddress'共享'Accounts'表,但是没有这种类型的实体具有相同的键值'Id:b7662057-44c2-4f3f-2cf0-08d504db1849'已被标记为"已添加"."
您必须添加构造函数并初始化拥有的实体。
public class Account
{
public Account (){
Address = new StreetAddress();
}
public GUID Id { get; set; }
public string Email { get; set; }
public StreetAddress Address { get; set; }
}
public class StreetAddress
{
public StreetAddress(){
Location = new Location();
}
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; }
}
Run Code Online (Sandbox Code Playgroud)
换句话说,不能有可选的拥有实体。
注意:如果您有一个非空构造函数,由于ef 核心限制,您还必须添加空构造函数。
| 归档时间: |
|
| 查看次数: |
3870 次 |
| 最近记录: |