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

问题描述 投票:0回答:1

我正在 xamarin 表单中使用 sqlite 创建一个项目,我遇到一个问题,在保存新项目页面上,我创建了我的 ITEM 模型的实例,并且在 ITEM 中引用了另一个模型,该模型是 PRIORITY,当我单击保存项目并将其保留在调试模式下,我可以接收所有项目,包括保存的优先级,但在我在 SQLite 中添加项目的变量中,它返回优先级,如下所示: 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);

        }

我无法访问其他模型的表格

sqlite xaml xamarin xamarin-forms-4
1个回答
0
投票

您可以尝试按如下方式修改您的代码:

1.为

public int ItemId { get; set; }
添加外键(
Priority.cs

 [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; }
}
  1. [ManyToOne]
    更改为
    OneToOne
    以获得
    Item.cs

    [表(“项目”)] 公开课项目 { [主键、自动增量] 公共 int Id { 得到;放; } 公共字符串名称{获取;放; } 公共字符串描述{获取;放; }

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

    }

  2. InsertPriority
    添加几个方法(
    UpdatePriority
    IItemsService.cs

    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.为类

InsertPriority
实现上述接口
UpdatePriority
ItemsService.cs

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.修改命令

ExecuteSaveItemsCommand
AddItemViewmodel.cs

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
}
© www.soinside.com 2019 - 2024. All rights reserved.