簡體   English   中英

EF 4.1首先使用代碼不創建新數據庫

[英]EF 4.1 using code first do not create new database

我使用帶有單獨層的Entity Framework 4.1代碼優先方法創建了一個新網站:

在模型層中,我定義類模型

在數據層中,我定義存儲庫類

在數據庫層中,我實現存儲庫類。 創建上下文,我實現了DbContext來定制我自己的表。

最后,我將各層的引用添加到網站(表示層)。 運行網站后,EF 4.1不會在App_Data文件夾中創建數據庫。 我想知道我做錯了哪些步驟。 請查看我的代碼並給我一些建議。 提前致謝 !

我只添加我認為其中包含錯誤的類的代碼。 模型層中的其他類模型和數據層中的類存儲庫與錯誤無關。 所以我不在這里寫。

web.config中:

<add name="ApplicationServices" connectionString="Data Source=DESKTOP\Neven;Initial Catalog=aspnetdb;Integrated Security=True" providerName="System.Data.SqlClient" />
      <add name="FashionShopData" connectionString="Data Source=|DataDirectory|FashionShopData.mdf;Initial Catalog=FashionShopData;Integrated Security=True" providerName="System.Data.SqlClient" />

在Global.asax中:

    protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ModelMetadataProviders.Current = new MetadataProvider();
            InitialDatabase();
        }

private static void InitialDatabase()
        {
            var repositoryInitializer = new RepositoryInitializer();
            repositoryInitializer.Initialize();
        }

在數據庫SQL層中:

上下文

    using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using FashionShop.Data.Repositories;
using FashionShop.Models;

namespace FashipShop.Data.Sql
{

    public partial class FashionShopContext : DbContext, IUnitOfWork
    {
        /// <summary>
        /// This method sets up the database appropriately for the available model objects.
        /// This method only sets up the data tier.  
        /// Any shared or model level requirements (data validations, etc) are on the model objects themselves.
        /// </summary>
        /// <param name="modelBuilder">The model builder object for creating the data model.</param>
        public FashionShopContext()
        : base("name=FashionShopData")
    {

    }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            SetupUserEntity(modelBuilder);

            SetupCategoryEntity(modelBuilder);

            SetupProductEntity(modelBuilder);

            SetupOrderEntity(modelBuilder);

        }

        private static void SetupUserEntity(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasKey(r => r.UserId);
            modelBuilder.Entity<User>().Property(r => r.UserId).HasDatabaseGeneratedOption(
                DatabaseGeneratedOption.Identity);

            modelBuilder.Entity<User>().HasMany(o => o.Orders);

            modelBuilder.Entity<User>().Property(r => r.Email).IsRequired();
        }

        private static void SetupCategoryEntity(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>().HasKey(c => c.CateId);
            modelBuilder.Entity<Category>().Property(c => c.CateId).HasDatabaseGeneratedOption(
                DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<Category>().Property(c => c.ParentId).IsOptional();
            modelBuilder.Entity<Category>().HasMany(p => p.Products);
        }

        private static void SetupProductEntity(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().HasKey(p => p.ProductId);
            modelBuilder.Entity<Product>().Property(p => p.ProductId).HasDatabaseGeneratedOption(
                DatabaseGeneratedOption.Identity);

            modelBuilder.Entity<Product>().HasRequired(c => c.Category).WithRequiredPrincipal().WillCascadeOnDelete(true);
        }

        private static void SetupOrderEntity(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Order>().HasKey(o => o.OrderId);
            modelBuilder.Entity<Order>().Property(o => o.OrderId).HasDatabaseGeneratedOption(
                DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<Order>().HasMany(p => p.Products).WithMany(o => o.Orders).Map(op =>
                                                                                                  {
                                                                                                      op.ToTable(
                                                                                                          "ProductOrder");
                                                                                                      op.MapLeftKey(
                                                                                                          "OrderId");
                                                                                                      op.MapRightKey(
                                                                                                          "ProductId");
                                                                                                  });
        }

        public DbSet<User> Users { get; set; }

        public DbSet<Category> Categories { get; set; }

        public DbSet<Product> Products { get; set; }

        public DbSet<Order> ShoppingCarts { get; set; }

        void IUnitOfWork.SaveChanges()
        {
            base.SaveChanges();
        }
    }
}

存儲庫初始化代碼:

    using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using FashionShop.Data.Repositories;

namespace FashipShop.Data.Sql
{
    public class RepositoryInitializer : IRepositoryInitializer
    {

        public RepositoryInitializer()
        {
            Database.DefaultConnectionFactory = new SqlConnectionFactory();
        }

        public void Initialize()
        {
            Database.SetInitializer(new CreateDatabaseIfNotExists<FashionShopContext>());
        }
    }
}

通用存儲庫:

    using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using FashionShop.Data.Repositories;


namespace FashipShop.Data.Sql.Repositories
{    
    public abstract class GenericRepository<T>: IGenericRepository<T> where T:class {
        protected IUnitOfWork UnitOfWork { get; set; }
        protected FashionShopContext Context { get { return (FashionShopContext)this.UnitOfWork; } }

        public GenericRepository(IUnitOfWork unitOfWork)
        {
            if (unitOfWork == null) throw new ArgumentNullException("unitOfWork");
            this.UnitOfWork = unitOfWork;
        }

        public virtual IQueryable<T> GetAll()
        {
            IQueryable<T> query  = Context.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = Context.Set<T>().Where(predicate);
            return query;
        }

        public virtual void Add(T entity)
        {
            Context.Set<T>().Add(entity);
            Context.SaveChanges();
        }

        public virtual void Delete(T entity)
        {
            Context.Set<T>().Remove(entity);
            Context.SaveChanges();
        }

        public virtual void Edit(T entity)
        {
            Context.Entry(entity).State = EntityState.Modified;
            Context.SaveChanges();
        }
    }



}

我發現了錯誤,因為我從未在表示層中使用代碼,所以EF不會初始化數據庫,因此我需要添加

FashionShopContext context = new FashionShopContext(); 
context.Database.Initialize(true);

進入Application_Start()。 但是在我更改了代碼之后,又出現了另一個錯誤:

"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server"

這是我使用的連接字符串:

<add name="FashionShopData" connectionString="Data Source=|DataDirectory|FashionShopData.mdf;Initial Catalog=FashionShopData;Integrated Security=True" providerName="System.Data.SqlClient" />

我的連接字符串錯誤嗎? 我該如何糾正?

嘗試..

<add name="ContextName" connectionString="Data Source=ServerName;Initial Catalog=DBCataloName;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"
   providerName="System.Data.SqlClient" />

您的問題是初始化在DbContext派生類上設置的連接字符串

它應該像下面這樣。

public partial class FashionShopContext : DbContext, IUnitOfWork
{

   public static string ConnectionString { get; set; }

   public FashionShopContext() : base(ConnectionString ?? "FashionShopData")
    {

    }
}

Global.asax

protected void Application_Start()
{
FashionShopContext.ConnectionString = ConfigurationManager.ConnectionStrings["FashionShopData"].ConnectionString;
}

希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM