如何使用实体框架在Xamarin中查询Sqlite? [英] How can I query Sqlite in Xamarin using Entity Framework?
问题描述
我正在使用Sqlite和EF插件(Microsoft.Enttityframeworkcore.sqlite)的Xamarin.Forms项目(C#).发生什么情况取决于:
I'm in a Xamarin.Forms project (C#) using Sqlite and EF plug-in (Microsoft.Enttityframeworkcore.sqlite). What happens depends:
方案1:我使用"Database.EnsureDeletedAsync"
Scenario 1: I use "Database.EnsureDeletedAsync"
- 我可以将数据放入数据库
- 在相同的"using"语句和"dbContext"对象中,我可以使用LINQ查询检索数据而没有错误.
方案2:我不使用"Database.EnsureDeletedAsync"
Scenario 2: I do not use "Database.EnsureDeletedAsync"
- 数据库已经存在
- 我可以向其中添加数据
- 在相同的"using"语句和"dbContext"对象中,任何使用LINQ查询检索数据的尝试(我尝试了多次 方式),导致错误(System.NullReferenceException:对象 引用未设置为对象的实例).
- the database already exists
- I can add data to it
- within the same "using" statement and "dbContext" object, any attempt to retrieve the data using LINQ query (I've tried multiple ways), results in error (System.NullReferenceException: Object reference not set to an instance of an object).
在两种情况下,我都可以ADB从Android模拟器中提取数据库并进行验证
In BOTH scenarios, I am able to ADB pull the db from the Android emulator and verify
1)数据库存在并且 2)我的数据正在处理中.
1) the db exists and 2) my data are going into it.
仅供参考-DbPath已验证正确(再次,我可以拉出数据库并查看其中的数据).
FYI - the DbPath is verified to be correct (again, I can pull the DB and see data in it).
// POCO class
public class Participant
{
[Key]
public int Id { get; set; }
public string Fname { get; set; }
}
// DB Context
public class DatabaseContext : DbContext
{
string _dbPath;
public DbSet<Participant> Participants { get; set; }
public DatabaseContext(string dbPath)
{
_dbPath = dbPath;
//Database.EnsureDeletedAsync();
//Database.EnsureCreatedAsync();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Filename={_dbPath}");
}
}
// Main page code-behind
InitializeComponent ();
// Create Database & Tables
using (var db = new DatabaseContext(App.DbPath))
{
// Insert Data
db.Add(new Participant() { Fname = "time: " + DateTime.Now.ToString() });
db.SaveChanges();
// Retrieve Data
// Next two lines receive error in scenario 2
var result2 = db.Participants.Where(xyz => xyz.Id == 1).ToList();
IEnumerable<Participant> p = db.Participants.ToList();
}
推荐答案
问题已解决!事实证明,这是dbContext以及定义的方式/位置与尝试使用它的位置.代码已经过重组,以确保在执行读写操作之前不会丢失上下文范围.
Problem solved! It turned out to be the dbContext and how/where that was defined vs. where it was attempted to be used. Code has been restructured to ensure not to lose the context scope before performing reads and writes.
这篇关于如何使用实体框架在Xamarin中查询Sqlite?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!