按照大家提供的方法都配置好了,也连上了,但是只创建了一个空数据库,无任何表和数据?运行时报错
这是什么原因?
代码如下:
webconfig
<system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite"/> <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.82.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" /> </DbProviderFactories> </system.data> <connectionStrings> <!--<add name="MusicStoreEntities" connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf" providerName="System.Data.SqlServerCe.4.0" />--> <add name="MusicStoreEntities" connectionString="Data Source=|DataDirectory|MvcMusicStore.db;Version=3;New=True;" providerName="System.Data.SQLite" /> </connectionStrings>
程序集也引用了并且复制到本地
实体类
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MusicStoreWeb.Models { public class Categorys { public int CategorysId { get; set; } public string Title { get; set; } public List<Products> Productss { get; set; } } }
数据库上下文
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MusicStoreWeb.Models { public class MusicStoreEntities : DbContext { public DbSet<Categorys> Categoryss { get; set; } public DbSet<Products> Productss { get; set; } //构建器 覆盖默认的约定 protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Map schemas //modelBuilder.Entity<Order>().ToTable("efdemo.Order"); //modelBuilder.Entity<Products>().Property(x => x.Description).IsMaxLength(); } } }
初始化数据
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MusicStoreWeb.Models { public class SampleData : DropCreateDatabaseIfModelChanges<MusicStoreEntities> { protected override void Seed(MusicStoreEntities context) { var categorys = new List<Categorys> { new Categorys { Title = "Rock" }, new Categorys { Title = "Jazz" } }; var products = new List<Products> { new Products{Title="Rock One", Categorys=categorys.Single(c => c.Title=="Rock"), Description=""}, new Products{Title="Jazz One", Categorys=categorys.Single(c => c.Title=="Jazz"), Description=""} }; //categorys.ForEach(a => context.Categoryss.Add(a)); products.ForEach(a => context.Productss.Add(a)); } } }
global.asax
protected void Application_Start()
{
System.Data.Entity.Database.SetInitializer(new MusicStoreWeb.Models.SampleData());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
运行后报错,查看发现未创建任何表
我知道,我用过这2个东西。sqlite不支持EF的codefirst 功能。但是支持其他模式,如数据库优先的模式。。
你要用EF创建表?
配置好后
EF会根据实体类自动创建对应表
但sqlite没成功,sql server可以
@黄阿伦: 顶一下你的贴吧 我没这么干过。没办法帮到你
我也遇到这样的问题了,不知道如何解决。