EF6+Sqlite注意事项
运行环境~VS2017+Win10
1.引用SQLite相关~
2.添加引用后,Web.config文件已经变化,修改部分地方及连接字符串~
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
<connectionStrings>
<add name="MusicStoreEntities" connectionString="Data Source=|DataDirectory|MvcMusicStore.db" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
3.编写相关实体类和连接上下文类
//实体类例
//同时指定 Table 特性,不指定只能使用 SqlQuery 进行查询
[Table("Artist")]
public class Artist { public int ArtistId { get; set; } public string Name { get; set; } }
//上下文类例 using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Web; namespace MusicStore.Models { public class MusicStoreEntities:DbContext { public MusicStoreEntities() : base("name=MusicStoreEntities") { } //重写该方法用于指定单数形式的表名,不重写这里的话,在实体类上指定 Table 特性 protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } public DbSet<Album> Albums { get; set; } //public virtual DbSet<Genre> Genres { get; set; } public DbSet<Genre> Genres { get; set; } } }
对SQLite数据库的使用进行测试~
MusicStoreEntities db = new MusicStoreEntities(); //var sql = "SELECT * FROM genre"; //var genres = db.Database.SqlQuery<Genre>(sql).ToList(); var genres = db.Genres.ToList(); return View(genres);
两种查询方式均能正常返回数据。