.NET Core中的一对多关系数据播种

时间:2019-10-29 00:13:09

标签: c# sql-server entity-framework .net-core

我无法通过OnModelCreating方法将数据播种到数据库中。

我想使用国家/地区城市为我的数据库设置种子,但是当他们拥有< em>一对多关系。

型号:

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);
        });
    }

上面的代码抛出:

  

“状态”类型不能标记为“拥有”,因为已经存在具有相同名称的非拥有实体类型。

当我尝试 AddMigration 时。

我的目标是为一个国家及其尊重的州和城市播种数据库。

1 个答案:

答案 0 :(得分:2)

Getting Started with EF CoreRelationships页面是一对多映射的很好示例。

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的Data Seeding包含一个用于一对多关系模型的数据播种示例。

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" });