使用EFCore连接SQLite
    		       		warning:
    		            这篇文章距离上次修改已过421天,其中的内容可能已经有所变动。
    		        
        		                
                要使用Entity Framework Core (EFCore) 连接SQLite数据库,你需要按照以下步骤操作:
- 安装EFCore包和SQLite数据库提供程序包。
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools- 定义你的数据模型。
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}- 创建数据库上下文。
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=blogging.db");
    }
}- 使用数据库上下文进行数据操作。
public class Program
{
    public static void Main()
    {
        using (var context = new BloggingContext())
        {
            // 添加一个新的Blog
            context.Blogs.Add(new Blog { Url = "http://sample.com" });
            context.SaveChanges();
 
            // 查询所有的Blog
            var blogs = context.Blogs.ToList();
        }
    }
}确保你的项目中有一个DbSet属性对应于你的每个数据模型。在OnConfiguring方法中,你需要指定SQLite数据库的连接字符串。
以上代码演示了如何使用EFCore连接到SQLite数据库,包括添加数据和查询数据。
评论已关闭