首页 > 解决方案 > 无法将成分对象传递给新的配方对象

问题描述

我在 SQLite 数据库中创建了 2 个表 - 成分和食谱。

Recipe 对象自然而然地使用成分对象。

我正在尝试做的两件事:从我的成分数据库中获取一个成分对象,并在创建新配方时将该成分对象设置为变量。

//此成分数据仅用于测试目的 - 这仍然不起作用。本节只是尝试将成分对象设置为配方对象中的成分 1 变量。

            InventoryItem theIngredient= new InventoryItem();

            theIngredient.ID = 500;
            theIngredient.Name = "Name";
            theIngredient.Size = "None";
            theIngredient.Stock = "None";


            Recipe recipe = new Recipe()
            {
                ID = (maxPK == null ? 1 : maxPK.ID + 1),
                Name = nameEntry.Text,
                Ingredient1 = theIngredient
            };
        db.Insert(recipe);

这是我得到的错误:

System.NotSupportedException Message=不知道 PantryShopper.Models.InventoryItem

这甚至不是我想要做的......

我想要做的是从数据库来源的选择器中选择成分,然后使用从选择器中选择的成分作为传递到新配方中的成分。但是,在那我似乎无法从数据库中访问该项目作为成分对象。我在考虑将该对象转换为数据库数据的方式,我可以从数据库中将它作为原始对象版本取回,还是我必须重建它(这也是我试图做的)?

        InventoryItem theIngredient= new InventoryItem();

        ingredient1Picker = new Picker();
        ingredient1Picker.ItemsSource = db.Table<InventoryItem>().OrderBy(x => x.Name).ToList();
        stackLayout.Children.Add(ingredient1Picker);

        inventoryItem = ingredient1Picker.SelectedItem;

然后将成分设置为选择器中当前选定的项目。但是,我收到错误消息:无法将类型“object”隐式转换为“PantryShop.Models.InventoryItem”,存在显式转换(您是否缺少演员表?)

无论如何,这是我在这里的第一篇文章。任何帮助深表感谢!干杯。

标签: c#databasesqliteobjectxamarin

解决方案


但是,我收到错误消息:无法将类型“object”隐式转换为“PantryShop.Models.InventoryItem”,存在显式转换(您是否缺少演员表?)

正如错误告诉您的那样,您需要将SelectedItem(对象)显式转换为InventoryItem

inventoryItem = (InventoryItem)ingredient1Picker.SelectedItem;

推荐阅读