我使用具有单独层的实体框架 4.1 代码优先方法创建了一个新的 Web:
在模型层,我定义了类模型
在数据层,我定义了存储库类
在数据库层,我实现了存储库类。创建上下文,我实现了 DbContext 来自定义我自己的表。
最后,我将图层的引用添加到网站(表示层)。运行我的网站后,EF 4.1 不在 App_Data 文件夹中创建数据库。我想知道我做错了哪些步骤。请查看我的代码并给我一些建议。提前致谢 !
我只是添加了我认为其中包含错误的类的代码。模型层中的其他类模型和数据层中的类存储库与错误无关。所以我不在这里写它们。
网络配置:
<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" />
我的连接字符串是错误的吗?我该如何纠正?