【发布时间】:2019-06-20 22:49:31
【问题描述】:
请来 Xamarin 和 MvvmCross 专家。我一直在尝试调试这个错误几个小时MvvmCross.Exceptions.MvxException: Failed to construct and initialize ViewModel for type TestApp.Core.ViewModels.IngredientsViewModel from locator MvxDefaultViewModelLocator。我找到了实际导致此错误的一段代码,它与使用 EFCore sqlite 从数据库中提取数据有关。
这是我第一次将它用于移动应用程序,所以也许你会发现一些我看不到的东西。以下是我认为足够的所有信息,如果需要更多信息,请告诉我!我希望该解决方案对其他人有所帮助。
请注意,当我注释掉 GetIngredients 时,我没有收到上述错误。
Core/Shared 项目中的我的应用文件
public class AppCore : MvxApplication
{
public override void Initialize()
{
Mvx.IoCProvider.RegisterType<TestContext>();
Mvx.IoCProvider.RegisterType<IIngredientRepository, IngredientRepository>();
RegisterAppStart<IngredientsViewModel>();
}
}
我的 DbContext
public class TestContext : DbContext
{
public TestContext() : base()
{
}
private const string _databaseName = "Test.db";
public DbSet<Ingredient> Ingredients { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string databasePath;
switch (Device.RuntimePlatform)
{
case Device.iOS:
SQLitePCL.Batteries_V2.Init();
databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", _databaseName); ;
break;
case Device.Android:
databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), _databaseName);
break;
default:
throw new NotImplementedException("Platform not supported");
}
optionsBuilder.UseSqlite($"Filename={databasePath}");
}
}
存储库
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> GetAll();
}
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly TestContext Context;
public Repository(TestContext context)
{
Context = context;
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList(); //after this line error is thrown
}
}
public interface IIngredientRepository : IRepository<Ingredient> {}
public class IngredientRepository : Repository<Ingredient>, IIngredientRepository
{
public IngredientRepository(TestContext testContext) : base(testContext)
{ }
}
我的视图模型
public class IngredientsViewModel : BaseViewModel
{
private IIngredientRepository IngredientRepository { get; set; }
public IngredientsViewModel(IIngredientRepository ingredientRepository)
{
IngredientRepository = ingredientRepository;
GetIngredients(); //when commented out, the view loads fine
}
private void GetIngredients()
{
var ingredients = IngredientRepository.GetAll();
Ingredients = new MvxObservableCollection<Ingredient>(ingredients);
}
private MvxObservableCollection<Ingredient> _ingredients;
public MvxObservableCollection<Ingredient> Ingredients
{
get => _ingredients;
set { SetProperty(ref _ingredients, value); }
}
}
【问题讨论】:
-
应该有一个内部异常,该异常具有嵌入在该 MvxException 中的更详细的错误消息。你能把那个贴出来吗?我的猜测是您的成分表尚未创建,这就是您在查询该表中的所有项目时遇到错误的原因。
-
@pnavk 你的意思是抛出错误后输出窗口中的信息吗?我看到很多 .db 文件没有找到。我认为这指向了下面的答案。非常感谢!
标签: c# sqlite xamarin xamarin.forms mvvmcross