如何在导航属性中播种?

时间:2017-11-22 10:09:24

标签: entity-framework-core

我在这个Db中有几个模型,

我正在使用以下种子类,我在启动时使用SeedData.Initialize(serviceProvider);初始化它,其中serviceProvider注入配置方法。

public class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ArtCoreDbContext(
                serviceProvider.GetRequiredService<DbContextOptions<ArtCoreDbContext>>()))
            {
                // Look for any movies.
                if (context.Genders.Any())
                {
                    return;   // DB has been seeded
                }

                context.Genders.AddRange(
                     new Genders
                     {
                         Name = "Male"
                     },

                     new Genders
                     {
                         Name = "Female"
                     }

                );
                context.SaveChanges();

                if (context.Statuses.Any())
                {
                    return;   // DB has been seeded
                }

                context.Statuses.AddRange(
                     new Statuses
                     {
                         Name = "Active"
                     },

                     new Statuses
                     {
                         Name = "Inactive"
                     },

                     new Statuses
                     {
                         Name = "Cancelled"
                     }


                );
                context.SaveChanges();

                if (context.PatientsRegistry.Any())
                {
                    return;   // DB has been seeded
                }

                context.PatientsRegistry.AddRange(
                     new PatientsRegistry
                     {
                        PatientFileId = 1234,
                        FirstName = "John",
                        SecondName = "M",
                        LastName = "Doe",
                        Gender = {Id = 5, Name="Male"},
                        Status = {Id = 2, Name="Inactive"}
                     }
                );
                context.SaveChanges();

            }
        }
    }

他们的模型是

public class Genders
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

public class Statuses
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


[Table("PatientsRegistry")]
    public class PatientsRegistry
    {   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long RecordId { get; set; }
        [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public long PatientFileId { get; set; }
        public string FirstName { get; set; }
        public string SecondName { get; set; }
        public string LastName { get; set; }
        public Genders Gender { get; set; }
        public Statuses Status { get; set; }
        public ICollection<PartnersRegistry> Partners { get; set; }

        public PatientsRegistry()
        {
            Partners = new Collection<PartnersRegistry>();
        }

    }

我成功播种两种模型(性别和状态)但不是患者注意事项!是导航。丙

我在这里错过了什么?

2 个答案:

答案 0 :(得分:1)

PatientsRegistry添加到GendersStatuses

public class Genders
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<PatientsRegistry> PatientsRegistries { get; set; }
}

public class Statuses
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<PatientsRegistry> PatientsRegistries { get; set; }
}

然后在OnModelCreating类中的方法ArtCoreDbContext内添加以下配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Genders>().HasMany(g => g.PatientsRegistries).WithOne(p => p.Gender);
    modelBuilder.Entity<Statuses>().HasMany(g => g.PatientsRegistries).WithOne(p => p.Status);

    base.OnModelCreating(modelBuilder);
}

将种子类更改为:

public class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using(var context = new ArtCoreDbContext(serviceProvider.GetRequiredService<DbContextOptions<ArtCoreDbContext>>())))
        {
            if (context.Genders.Any() && context.Statuses.Any() && context.PatientsRegistries.Any())
                return; // DB has been seeded

            var g1 = new Genders { Name = "Male" };
            var g2 = new Genders { Name = "Female" };
            context.Genders.AddRange(new[] { g1, g2 });

            var s1 = new Statuses { Name = "Active" };
            var s2 = new Statuses { Name = "Inactive" };
            var s3 = new Statuses { Name = "Canceled" };
            context.Statuses.AddRange(new[] { s1, s2, s3 });

            context.PatientsRegistries.AddRange(
                new PatientsRegistry
                {
                    PatientFileId = 1234,
                    FirstName = "John",
                    SecondName = "M",
                    LastName = "Doe",
                    Gender = g1,
                    Status = s1
                },
                new PatientsRegistry
                {
                    PatientFileId = 1235,
                    FirstName = "Julia",
                    SecondName = "M",
                    LastName = "Doe",
                    Gender = g2,
                    Status = s2
                }
            );

            context.SaveChanges();
        }
    }
}

答案 1 :(得分:0)

这是解决方案,Ref为here,由Edward Z

回答
 context.PatientsRegistry.AddRange(
           new PatientsRegistry
                     {
                         PatientFileId = 1234,
                         FirstName = "John",
                         SecondName = "M",
                         LastName = "Doe",                        
                         Gender = context.Genders.Where(g => g.Name == "Male").FirstOrDefault(),
                         Status = context.Statuses.Where(s => s.Name == "Inactive").FirstOrDefault()
                     }
                );

另一种解决方案是向PatientsRegistry添加两个新道具以及Navigation Prop

public int GenderId { get; set; }
public int StatusId { get; set; }
public class Genders
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

public class Statuses
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

[Table("PatientsRegistry")]
    public class PatientsRegistry
    {   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long RecordId { get; set; }
        [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public long PatientFileId { get; set; }
        public string FirstName { get; set; }
        public string SecondName { get; set; }
        public string LastName { get; set; }
        public int GenderId { get; set; }
        public Genders Gender { get; set; }
        public int StatusId { get; set; }
        public Statuses Status { get; set; }
        public ICollection<PartnersRegistry> Partners { get; set; }

        public PatientsRegistry()
        {
            Partners = new Collection<PartnersRegistry>();
        }

    }

现在基于这个模型,流畅的API将创建一个带有删除的Cascade RI的外键,sql server不接受所以我将其更改为 onDelete: ReferentialAction.Restrict);

现在在我的种子课上,我可以按如下方式选择Id值(我稍微修改了一下),

 if (!context.PatientsRegistry.Any())
                {
                    context.PatientsRegistry.AddRange(
                     new PatientsRegistry
                     {
                        PatientFileId = 1234,
                        FirstName = "John",
                        SecondName = "M",
                        LastName = "Doe",
                        GenderId = 1,
                        StatusId = 2
                     }
                );
                context.SaveChanges();
                }