gpt4 book ai didi

c# - 保存时拥有的类型映射EF Core失败

转载 作者:行者123 更新时间:2023-12-03 04:38:18 24 4
gpt4 key购买 nike

我想使用拥有的类型进行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);

我得到这个错误

Message "The entity of 'Account' is sharing the table 'Accounts' with 'Account.Address#StreetAddress', but there is no entity of this type with the same key value 'Id:b7662057-44c2-4f3f-2cf0-08d504db1849' that has been marked as 'Added'."

最佳答案

您必须添加构造函数并初始化拥有的实体。

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; }
}
换句话说,不能有可选的拥有实体。
注意:如果您有一个非空的构造函数,由于 ef core limitations.,还必须添加一个空的构造函数

关于c# - 保存时拥有的类型映射EF Core失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46420974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com