EntityFramework核心代码优先迁移Complex类型

时间:2019-07-19 08:31:52

标签: entity-framework-core-2.1 entity-framework-core-2.2

我正在使用ef core创建一个基本应用程序。在其中,我有一个Person和Address类。地址是一种复杂的类型。当我尝试使用软件包管理器concole运行迁移命令(add-migration initialmigration)时。它引发异常。它说我必须为此复杂类型定义Id。下面是以下代码。

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public ICollection<Address> Addresses { get; set; }
}

public class Address 
{
    public String Street { get; private set; }


    private Address()
    {
    }

    public Address(string street)
    {
        Street = street;

    }       
}

public class MyContext : DbContext
{
    public MyContext() { 


    }

    DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Server=.;Database=MyTest;Trusted_Connection=True;");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().Property(k => k.Id).ValueGeneratedOnAdd();

        modelBuilder.Entity<Person>(entity => entity.OwnsMany(m => m.Addresses, address => 

            address.Property(x => x.Street).HasColumnName("Street")

            ));
    }
}

我该如何解决此问题,以便迁移复杂的类型。

任何帮助将不胜感激。

0 个答案:

没有答案