gpt4 book ai didi

c# - Entity Framework Core SQLite with Xamarin.Forms 不更新 Db

转载 作者:行者123 更新时间:2023-12-04 15:29:52 24 4
gpt4 key购买 nike

我正在制作一个带有 Entity Framework Core SQLite 的 Xamarin.Forms MVVM 应用程序,以在手机本地保存一个 Db。

我生成了 Db 和一些初始项目,稍后通过 App 我添加了一个新项目,目前它工作正常(刷新 App 中的 ListView 并正确显示所有项目)。

问题是当我想更新 Db 中的一项时。我更新了项目但没有在 ListView 中更新。它在 ListView 中更新的唯一方法是重新启动 de App。

如何使用更新的项目刷新 ListView ?

这是数据上下文代码:

public class DataContext : DbContext
{
public DataContext() : base()
{
//Database.EnsureDeleted();
Database.EnsureCreated();
}

public DbSet<Sensor> Sensors { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Filename={Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "database.sqlite")}");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Sensor>(s =>
{
s.HasKey(en => en.Id);
//s.HasIndex(en => en.ClientId).IsUnique();
s.Property(en => en.Name).IsRequired();
});
modelBuilder.Entity<Sensor>()
.HasData(
new Sensor { Id = Guid.NewGuid().ToString(), ClientId = "11111", Name = "First item", Description = "This is a private item description.", Payload = "Off" },
new Sensor { Id = Guid.NewGuid().ToString(), ClientId = "11112", Name = "Second item", Description = "This is a shopping item description.", Payload = "Off" },
new Sensor { Id = Guid.NewGuid().ToString(), ClientId = "11113", Name = "Third item", Description = "This is a work item description.", Payload = "Off" }
);
}

这是 MainPageViewModel 代码:

    public class MainPageViewModel : ViewModelBase
{
private readonly INavigationService _navigationService;
private readonly DataContext _dataContext;
private static MainPageViewModel _instance;
private DelegateCommand _addSensorCommand;
private ObservableCollection<SensorItemViewModel> _sensors;

public MainPageViewModel(
INavigationService navigationService,
DataContext dataContext) : base(navigationService)
{
_navigationService = navigationService;
_dataContext = dataContext;
_instance = this;
LoadSensors();
}

public DelegateCommand AddSensorCommand => _addSensorCommand ?? (_addSensorCommand = new DelegateCommand(AddSensor));

public ObservableCollection<SensorItemViewModel> Sensors
{
get => _sensors;
set => SetProperty(ref _sensors, value);
}

public static MainPageViewModel GetInstance()
{
return _instance;
}

private async void AddSensor()
{
await _navigationService.NavigateAsync("SensorPage", null);
}

public async void LoadSensors()
{
try
{
var _sensors = await _dataContext.Sensors.ToListAsync();
Sensors = new ObservableCollection<SensorItemViewModel>(_sensors.Select(s => new SensorItemViewModel(_navigationService)
{
Id = s.Id,
ClientId = s.ClientId,
Name = s.Name,
Description = s.Description,
Payload = s.Payload
}).ToList());
}
catch (Exception ex)
{
await App.Current.MainPage.DisplayAlert("Error", ex.Message, "Aceptar");
}
}
}

这是 SensorPageViewModel 代码:

    public class SensorPageViewModel : ViewModelBase
{
private readonly INavigationService _navigationService;
private readonly DataContext _dataContext;
private DelegateCommand _addCommand;
private Sensor _sensor;
private string _buttonText;

public SensorPageViewModel(
INavigationService navigationService,
DataContext dataContext) : base(navigationService)
{
_navigationService = navigationService;
_dataContext = dataContext;
}

public DelegateCommand AddCommand => _addCommand ?? (_addCommand = new DelegateCommand(Add));

public string ButtonText
{
get => _buttonText;
set => SetProperty(ref _buttonText, value);
}

public Sensor Sensor
{
get => _sensor;
set => SetProperty(ref _sensor, value);
}

public override void OnNavigatedTo(INavigationParameters parameters)
{
base.OnNavigatedTo(parameters);

if (parameters.Count >= 1)
{
var parameterSensor = parameters.GetValue<SensorItemViewModel>("Sensor");
Sensor = new Sensor()
{
Id = parameterSensor.Id,
ClientId = parameterSensor.ClientId,
Name = parameterSensor.Name,
Description = parameterSensor.Description,
Payload = parameterSensor.Payload
};
Title = Sensor.Name;
ButtonText = "Editar";
}
else
{
Sensor = new Sensor();
Title = "Nuevo sensor";
ButtonText = "Salvar";
}
}

private async void Add()
{
if (ButtonText == "Editar")
{
ButtonText = "Salvar";
Title = "Editar";

return;
}

try
{
if (Title == "Editar")
{
_dataContext.Sensors.Update(Sensor);
await _dataContext.SaveChangesAsync();
}
else
{
Sensor.Id = Guid.NewGuid().ToString();
_dataContext.Sensors.Add(Sensor);
await _dataContext.SaveChangesAsync();
}
}
catch (Exception ex)
{
await App.Current.MainPage.DisplayAlert("Error", ex.Message, "Aceptar");

return;
}

MainPageViewModel.GetInstance().LoadSensors();
await _navigationService.GoBackAsync();
}
}

这是 SensorItemViewModel 代码:

public class SensorItemViewModel : Sensor
{
private readonly INavigationService _navigationService;
private DelegateCommand _selectSensorCommand;

public SensorItemViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
}

public DelegateCommand SelectSensorCommand => _selectSensorCommand ?? (_selectSensorCommand = new DelegateCommand(SelectSensor));

private async void SelectSensor()
{
var parameters = new NavigationParameters
{
{"Sensor", this}
};

await _navigationService.NavigateAsync("SensorPage", parameters);
}
}

最佳答案

我调试了程序流程,发现当我更新项目并保存 _dataContext 时在SensorViewModel它没有出现在 MainPageViewModel 中.

保存更新项在SensorViewModel我添加了 Actualizado在名称中:

introducir la descripción de la imagen aquí

但是当我读到 de _dataContextMainViewModel它没有出现:

introducir la descripción de la imagen aquí

当我添加一个新项目时,它工作正常,没有问题。

关于c# - Entity Framework Core SQLite with Xamarin.Forms 不更新 Db,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61438267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com