简体   繁体   English

访问从 SQLite 数据库返回的字符串任务的字段时出现错误

[英]Accessing fields of a string task returned from SQLite Database is giving errors

In my Xamarin application I have a local db set up using SQLite.在我的 Xamarin 应用程序中,我使用 SQLite 设置了一个本地数据库。 I have followed the microsoft to-do list example when setting this up ( https://docs.microsoft.com/en-gb/xamarin/xamarin-forms/data-cloud/data/databases ) however I have hit an issue.我在设置时遵循了微软待办事项列表示例( https://docs.microsoft.com/en-gb/xamarin/xamarin-forms/data-cloud/data/databases )但是我遇到了一个问题。

I have a model called "Animal" which is saved into my database and what I am trying to query the fields of:我有一个名为“Animal”的 model 保存到我的数据库中,我正在尝试查询以下字段:

    public int ID { get; set; }

    public string Name {get; set; }
    
    public string Species { get; set; }
  
    public string Markings { get; set; }
   
    public string Diet { get; set; }

Within my database query file I am trying to perform a query that will get the animal based upon it's name which is given by the user and then from this it will return its markings/diet/etc... This is what I have so far but it is erroring and I am really not sure on how to fix it:在我的数据库查询文件中,我正在尝试执行一个查询,该查询将根据用户给出的动物名称获取动物,然后从中返回其标记/饮食/等...这就是我到目前为止所拥有的但它出错了,我真的不确定如何修复它:

    public async Task<string> getanimaldiet(string name)
    {
        
            Animal a = Database.Table<Animal>().Where(x => x.Name == name).FirstOrDefaultAsync();
            return a.Diet;


    }

Errors: The name 'diet' does not exist in the current context & Cannot implicitly convert type 'System.Threading.Tasks.Task<animalService.Animal>' to 'animalService.Animal'错误:当前上下文中不存在名称 'diet' 并且无法将类型 'System.Threading.Tasks.Task<animalService.Animal>' 隐式转换为 'animalService.Animal'

Any help is much appreciated.任何帮助深表感谢。

Since you have async api you need to add await to your code:由于您有异步 api 您需要在代码中添加等待:

 Animal a =  await Database.Table<Animal>().Where(x => x.Name == name) 
               .FirstOrDefaultAsync();

            return a.Diet;

You can make it sync:你可以让它同步:

public string getanimaldiet(string name)
    {
      
Animal a =   Database.Table<Animal>().Where(x => x.Name == name) 
               .FirstOrDefault();

            return a.Diet;
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM