XAML 当我将项目保存在xamarin表单中时,如何从一个模型中访问另一个模型中的项目

r8xiu3jd  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(83)

我正在xamarin表单中使用sqlite创建一个项目,我遇到了一个问题,在保存新项目页面上,我创建了我的项目模型的示例,并在项目中引用了另一个模型,即优先级,当我单击保存项目并将其置于调试模式时,我可以接收所有项目,包括保存的优先级,但在我添加SQLite中的项的变量中,它返回PRIORITY如下:ItemPriority = {CrudTasks.Models.Priority}
当我试图访问这些项目上的视图页面我得到没有回应。

//Function SaveItems
        private async void ExecuteSaveItemsCommand()
        {
            try
            {

                Item itemSaved = new Item
                {
                    Name = NameSave,
                    Description = DescriptionSave,
                    ItemPriority = new Priority()
                    {
                        PriorityName = PrioritySave,
                        PriorityColor = "#ccc"
                    }
                };

                _itemsService.InsertItem(itemSaved);
                ExecuteBackProductPageCommand();

            }
            catch (Exception ex)
            {
                await Shell.Current.DisplayAlert("Error", ex.Message, "OK");
            }
        }
//Model Item
namespace CrudTarefas.Models
{
    [Table("Items")]
    public class Item
    {
        [PrimaryKey, AutoIncrement] 
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        [ManyToOne]
        public Priority ItemPriority { get; set; }
        
    }
}
//Model Priority
namespace CrudTarefas.Models
{
    [Table("Priorities")]
    public class Priority
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string PriorityName { get; set; }
        public string PriorityColor { get; set; }
    }
}
//CollectionView ListItemsPage
<ScrollView VerticalScrollBarVisibility="Never">
                <StackLayout>
                    <CollectionView ItemsSource="{Binding ItemsList}">
                        <CollectionView.ItemsLayout>
                            <LinearItemsLayout ItemSpacing="20" Orientation="Vertical" />
                        </CollectionView.ItemsLayout>
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <StackLayout>
                                    <Grid
                                        Margin="0,0,0,20"
                                        Padding="10"
                                        xct:CornerRadiusEffect.CornerRadius="12"
                                        BackgroundColor="{Binding ItemPriority.PriorityColor}"
                                        RowDefinitions="*,20,20"
                                        RowSpacing="10">
                                        <Frame
                                            Grid.Row="0"
                                            Padding="5"
                                            HorizontalOptions="Start">
                                            <Label Text="{Binding ItemPriority.PriorityName}" />
                                        </Frame>
                                        <Label
                                            Grid.Row="1"
                                            Text="{Binding Name}"
                                            TextColor="Black" />
                                        <Label
                                            Grid.Row="2"
                                            Text="{Binding Description}"
                                            TextColor="Black" />
                                    </Grid>
                                </StackLayout>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>
                </StackLayout>
            </ScrollView>
//Viewmodel ListItems
 -> In the LOADITEMS method in the commented code, I can access the static item with the collectionView

#region constructor
        public ListItemsViewmodel(INavigation navigation)
        {
            Navigation = navigation;
            _itemsService = new ItemsService();
            LoadItems();
            GoAddItemPageCommand = new Command(ExecuteGoAddItemPageCommand);
            LoadItemsCommand = new Command(ExecuteLoadItemsCommand);
        }
        #endregion

        #region commands 
        public ICommand GoAddItemPageCommand { get; set; }
        public ICommand LoadItemsCommand { get; set; }
        #endregion

        #region methods
  ->    private void LoadItems()
        {
            var items = _itemsService.GetAllItems();
            ItemsList = new ObservableCollection<Item>(items);

        }

我无法访问另一个模型的表

mefy6pfw

mefy6pfw1#

根据你的代码,我创建了一个演示,并在我这边实现了这个功能。
你可以尝试修改你的代码如下:
1.为Priority.cs添加外键(public int ItemId { get; set; }

[Table("Priorities")]
public class Priority
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string PriorityName { get; set; }
    public string PriorityColor { get; set; }

   [ForeignKey(typeof(Item))]
    public int ItemId { get; set; }
}

字符串
2.将Item.cs[ManyToOne]更改为OneToOne

[Table("Items")]
public class Item
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    //add attribute  OneToOne
    [OneToOne]
    public Priority ItemPriority { get; set; }
   
}


3.为IItemsService.cs添加几个方法(InsertPriorityUpdatePriority

public interface IItemsService
   {
    List<Item> GetAllItems();

    void InsertItem(Item item);

    //add  method InsertPriority
    void InsertPriority(Priority item);

    //add  method UpdatePriority
    void UpdatePriority(Priority item);

    void UpdateItem(Item item);
    void DeleteItem(int id);
    bool ExistsItem(string name, string description, string priorityName);
   }


4.为类ItemsService.cs实现以上接口InsertPriorityUpdatePriority
我们还需要将方法GetAllItems()上的代码var items = _connection.Table<Item>().ToList();替换为代码var items = _connection.GetAllWithChildren<Item>();

public class ItemsService : IItemsService
{
    private SQLiteConnection _connection;

    public ItemsService()
    {
        SetupDb();
    }

    private void SetupDb()
    {
        if(_connection == null)
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ItemsDb.db3");

            _connection = new SQLiteConnection(dbPath);
            _connection.CreateTable<Item>();
            _connection.CreateTable<Priority>();
        }
    }

    public void InsertItem(Item item)
    {
        _connection.Insert(item);
    }

    public void UpdateItem(Item item)
    {
        // _connection.Update(item);

        // replace above code with the following code
        _connection.UpdateWithChildren(item);
    }

    public void DeleteItem(int id)
    {
        _connection.Delete(id);
    }

    public List<Item> GetAllItems()
    {
        //var items = _connection.Table<Item>().ToList();

         // replace above code with the following code
        var items = _connection.GetAllWithChildren<Item>();

        return items;
    }

    public bool ExistsItem(string name, string description, string priorityName)
    {
        var existsItem = _connection.Table<Item>().FirstOrDefault(it => it.Name == name && it.Description == description
        && it.ItemPriority.PriorityName == priorityName);
        return existsItem != null;
    }

    public void InsertPriority(Priority item)
    {
        _connection.Insert(item);
    }

    public void UpdatePriority(Priority item)
    {
        _connection.Update(item);
    }
}


5.修改AddItemViewmodel.csExecuteSaveItemsCommand命令

public class AddItemViewmodel : BaseViewmodel
{
   
  //For the sake of simplicity, omit the other codes

    #region methods

    //Function SaveItems
    private async void ExecuteSaveItemsCommand()
    {
        try
        {

            Item itemSaved = new Item()
            {
                Name = NameSave,
                Description = DescriptionSave,
                //ItemPriority = new Priority
                //{
                //    PriorityName = PrioritySave,
                //    PriorityColor = "#ccc"
                //}
            };

            // _itemsService.InsertItem(itemSaved);

            Priority ItemPriority = new Priority
            {
                PriorityName = PrioritySave,

                PriorityColor = "#ccc"
            };

            _itemsService.InsertItem(itemSaved);

            _itemsService.InsertPriority(ItemPriority);
            itemSaved.ItemPriority = ItemPriority;

            _itemsService.UpdateItem(itemSaved);
            _itemsService.UpdatePriority(ItemPriority);

            ExecuteBackProductPageCommand();

        }
        catch (Exception ex)
        {
            await Shell.Current.DisplayAlert("Error", ex.Message, "OK");
        }
    }

    private async void ExecuteBackProductPageCommand()
    {
        await Navigation.PopAsync();
    }
    #endregion
}

相关问题