为什么我的本地数据库(SQL Server)没有种子任何数据

时间:2019-09-02 08:44:49

标签: c# sql asp.net .net sql-server

我正在使用MVC dotnet框架。我有客户模型  如下:

Model Before

     using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.Data.Entity;
        using System.Linq;
        using System.Web;

        namespace WebApplication5.Models
        {
            public class CustomerContext : DbContext
            {
                public CustomerContext() : base("CustomerDB")
                {
                    Database.SetInitializer(new        DropCreateDatabaseIfModelChanges<CustomerContext>());
                }

                public DbSet<Customer> Customers { get; set; }
            }
            public class Customer
            {
                public int id { get; set;}
                [Required]
                [StringLength(255)]
                public String Name { get; set;}
                public bool IsSubscribedToNewsletter { get; set;}
                public MembershipType MembershipType { get; set;}
                public byte MembershipTypeId { get; set; }
            }
        }
Model After 
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using WebApplication5.Configurations;

    namespace WebApplication5.Models
    {
        public class CustomerContext : DbContext
        {
            public CustomerContext() : base("CustomerContext")
            {
                Database.SetInitializer<CustomerContext>(new CustomerDBInitializer());
            }

                  public DbSet<Customer> Customers { get; set; }
        }


        public class Customer
        {
            public int id { get; set;}
            [Required]
            [StringLength(255)]
            public String Name { get; set;}
            public bool IsSubscribedToNewsletter { get; set;}
        }
    }

下面是我的代码播种CustoemrRepository,它具有删除,更新,编辑和添加客户表中的客户的所有功能:

        using System;
        using System.Collections.Generic;
        using System.Data.Entity;
        using System.Linq;
        using System.Web;
        using WebApplication5.Models;


        namespace WebApplication5.Repositories.CustomersRepositories
        {
            public class CustomerRepository : ICustomerRepository, IDisposable
            {
                private CustomerContext context;

                public CustomerRepository(CustomerContext context)
                {
                    this.context = context;
                }
                public IEnumerable<Customer> GetCustomers()
                {
                    return context.Customers.ToList();
                }
                public Customer GetCustomerByID(int Id)
                {
                    return context.Customers.Find(Id);
                }
                public void InsertCustomer(Customer customer)
                {
                    context.Customers.Add(customer);
                }
                public void DeleteCustomer(int Id)
                {
                    Customer customer = context.Customers.Find(Id);
                    context.Customers.Remove(customer);
                }
                public void UpdateCustomer(Customer customer)
                {
                    context.Entry(customer).State = EntityState.Modified;
                }
                public void Save()
                {
                    context.SaveChanges();
                }

                private bool disposed = false;
                protected virtual void Dispose(bool disposing)
                {
                    if (!this.disposed)
                    {
                        if (disposing)
                        {
                            context.Dispose();
                        }
                    }
                    this.disposed = true;
                }

                public void Dispose()
                {
                    Dispose(true);
                    GC.SuppressFinalize(this);
                }
            }
        }

这是我的customerController:

        using System;
        using System.Collections.Generic;
        using System.Data.Entity;
        using System.Linq;
        using System.Web;
        using System.Web.Routing;
        using System.Web.Mvc;
        using WebApplication5.Models;
        using WebApplication5.Repositories.CustomersRepositories;

        namespace WebApplication5.Controllers
        {
            //[RoutePrefix("api/customers")]
            public class CustomersController : Controller
            {
                private ICustomerRepository iCustomerRepository;

                public CustomersController()
                {
                    this.iCustomerRepository = new CustomerRepository(new CustomerContext());
                }


                public CustomersController(CustomerRepository customerRepository)
                {
                    this.iCustomerRepository = customerRepository;
                }

                [Route("customers")]
                [HttpGet]
                // GET: Customers
                public ActionResult Index()
                {
                    var customers = iCustomerRepository.GetCustomers();
                    //return View(customers);
                    return Content("Hey");
                }
            }
        }

之后,我进行了迁移,从而制作了本地数据库(Sql Server)和客户表。 然后,我添加了另一个文件,该文件将数据植入数据库: 我在包管理器中运行了migrations update命令,但是我的客户表仍然没有显示任何数据,并且为空。请帮忙   更新的种子数据文件

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using WebApplication5.Models;
        using WebApplication5.Repositories.CustomersRepositories;

        namespace WebApplication5
        {
                 public class CustomerDBInitializer : DropCreateDatabaseAlways<CustomerContext>
{
    protected override void Seed(CustomerContext context)
    {
        IList<Customer> customers = new List<Customer>
        {
            new Customer { id = 1, Name = "Jojo", IsSubscribedToNewsletter = true }
        };
        var customer1 = new Customer { id = 1, Name = "Jojo", IsSubscribedToNewsletter = true };
        context.Customers.AddRange(customers);

        base.Seed(context);
    }
}            }

    [my customer table is still empty][1]


      [1]: https://i.stack.imgur.com/PJoLm.png

1 个答案:

答案 0 :(得分:0)

-------------------------------------------------- -使用.NET EF6 ------------------------------------------- --------------

   public CustomerContext() : base("CustomerContext")
{

}

在运行“ Enable-Migrations”时生成的“ Configuration.cs”中,seed方法是添加代码以填充数据库的位置。


   protected override void Seed(WebApplication1.CustomerContext context)
    {

        IList<Customer> customers = new List<Customer>
        {
            new Customer { id = 1, Name = "Jojo", IsSubscribedToNewsletter = true },
               new Customer { id = 2, Name = "Jojo", IsSubscribedToNewsletter = true }
        };

        context.Customers.AddRange(customers);

        base.Seed(context);

    }

-------------------------------------------------- ---使用.NET EF CORE ------------------------------------------ --------------- 我认为您的CustomerContext错误,请尝试使用此方法。要在执行迁移时添加数据,请将此数据添加到OnModelCreating方法。

    public CustomerContext() : base()
    {
    }
    public CustomerContext(DbContextOptions<CustomerContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    { 
        string connectionString = "Server=localhost; Initial Catalog=TestCustomers;persist security info=True; Integrated Security = SSPI;";
        optionsBuilder.UseSqlServer(connectionString);
    }
    public DbSet<Customer> Customers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Customer>().HasData(
            new Customer { id = 1, Name = "Jojo", IsSubscribedToNewsletter = true} 
        );

    }