MVC Code First Approach不会为表格提供种子数据。我们是否需要启用迁移?

时间:2017-05-18 11:28:47

标签: asp.net-mvc ef-code-first

使用以下类创建的表..

 public class Country
    {
        [Key]
        public int CountryId { get; set; }

        [Display(Name = "Country Name")]
        [Required]
        public string CountryName { get; set; }

        [Display(Name = "Country Code")]
        [Required]
        public string CountryCode { get; set; }
    }

DBContext类继承

public class DatabaseContext:DbContext
{
    public DatabaseContext() : base("StudentContext")
    {
       Database.SetInitializer(new DatabaseRepository());
    }
    public DbSet<Country> Countrys { get; set; }

}

Web.Config 连接字符串

<add name="StudentContext" connectionString="Server=XXXXXX; Database=StudentDB; User Id=xxxxxxx; password=xxxxxxx" providerName="System.Data.SqlClient" />

覆盖种子方法的类

 public class DatabaseRepository :DropCreateDatabaseIfModelChanges<DatabaseContext>
    {


        protected override void Seed(DatabaseContext context)
        {

            Country _country = new Country();
            _country.CountryName = "India";
            _country.CountryCode = "IN";
            context.Countrys.Add(_country);
            context.SaveChanges();
            base.Seed(context);
        }
    }

使用MVC Web应用程序我正在尝试列出国家/地区列表。 代码能够使用此方法创建数据库和表,但不执行种子方法。

我确实尝试了解一些可用的视频并进行相应的更改,但似乎没有执行种子方法。

2 个答案:

答案 0 :(得分:0)

您还需要此属性:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

像:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }

自动生成列。请参阅this for an explanation

答案 1 :(得分:0)

尝试在配置文件构造函数中将AutomaticMigrationsEnabled设置为true,如下例所示

我的工作代码:

internal sealed  class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
    public Configuration()
            {
                AutomaticMigrationsEnabled = true;
            }
     protected override void Seed(ApplicationDbContext context)
        {
        }
}

注意:以上代码自动运行种子并将数据放入数据库

在您的情况下:

 public class DatabaseRepository :DbMigrationsConfiguration<DatabaseContext >
    {

    public  DatabaseRepository()
    {
      AutomaticMigrationsEnabled = true;
    }
      protected override void Seed(DatabaseContext context)
    {

        Country _country = new Country();
        _country.CountryName = "India";
        _country.CountryCode = "IN";
        context.Countrys.Add(_country);
        context.SaveChanges();
        base.Seed(context);
    }
}

看到它的作品,请让我知道你的想法或反馈

由于

KARTHIK