[英]One To Many relationship data seeding in .NET Core
我在使用OnModelCreating
方法將數據播種到我的數據庫時遇到問題。
我想用Country 、 States和Cities播種我的數據庫,但是當它們具有一對多關系時,我不知道該怎么做。
楷模:
public class City
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual State State { get; set; }
}
public class State
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<City> Cities { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<State> States { get; set; }
}
語境:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// ....
modelBuilder.Entity<State>()
.HasMany(p => p.Cities)
.WithOne(c => c.State)
.IsRequired();
modelBuilder.Entity<Country>()
.HasMany(s => s.States)
.WithOne(s => s.Country)
.IsRequired();
var BsAs = new State
{
Id = 1,
Name = "Buenos Aires",
};
var Argentina = new Country
{
Id = 1,
Name = "Argentina",
States = new[] { BsAs }
};
modelBuilder.Entity<Country>(s => {
s.HasData(Argentina);
s.OwnsMany(e => e.States).HasData(BsAs);
});
}
上面的代碼拋出:
無法將類型“State”標記為擁有,因為已存在同名的非擁有實體類型。
當我嘗試AddMigration時。
我的目標是用一個國家及其尊重的州和城市為數據庫播種。
EF Core 入門和關系頁面有一個很好的一對多映射示例。
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
在您的情況下, City
需要擁有StateId
,而State
需要擁有CountryId
。
public class City
{
public int Id { get; set; }
(...)
public int StateId { get; set; }
public State State { get; set; }
}
public class State
{
public int Id { get; set; }
(...)
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
}
EF Core 的 數據播種包含一對多關系 model 的播種數據示例。
modelBuilder.Entity<Blog>().HasData(new Blog {BlogId = 1, Url = "http://sample.com"}); modelBuilder.Entity<Post>().HasData( new Post() { BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1" });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.