Я реализовал метод CreateAsync в своем dbContext, чтобы добавить тренировку объект в базу данных и сохраните изменения с помощью SaveChangesAsync. Кроме того, у меня есть метод WorkoutManager.CreateAsync, который сериализует объект Workout в JSON и отправляет его на конечную точку сервера с помощью запроса HTTP POST.
Вот краткое описание ключевых компонентов:
Код: Выделить всё
//The command initializing the data entering
public ICommand CompleteWorkoutCommand => new Command(CompleteWorkout);
private async void CompleteWorkout()
{
Workout workout = new Workout();
workout.ExerciseTypeGroups = new List(ExerciseTypeGroups);
string userIdString = Preferences.Get("UserID", defaultValue: null);
if (int.TryParse(userIdString, out int userId))
{
// If parsing was successful, set the CreatorId property
workout.CreatorId = userId;
workout.Creator = await UserManaging.ReadAsync(userId);
// Create the workout asynchronously
Task.Run(() => WorkoutManager.CreateAsync(workout)).GetAwaiter().GetResult();
}
else
{
// Handle the case where parsing fails
Console.WriteLine("Failed to parse user ID from preferences.");
// You might want to handle this error case appropriately for your application
}
}
Код: Выделить всё
// DbContext method to add Workout object to the database
public async Task CreateAsync(Workout item)
{
try
{
dbContext.Workouts.Add(item);
await dbContext.SaveChangesAsync();
}
catch (Exception ex)
{
// Handle exception
throw;
}
}
Код: Выделить всё
// Workout class definition
public class Workout
{
[Key]
public int WorkoutId { get; set; }
public List ExerciseTypeGroups { get; set; }
public int CreatorId { get; set; }
public User Creator { get; set; }
public Status Status { get; set; }
public Workout()
{
ExerciseTypeGroups = new List();
}
public Workout(User user)
{
Status = Status.Waiting;
Creator = user;
ExerciseTypeGroups = new List();
}
}
Код: Выделить всё
// Manager method to send Workout object to server endpoint
public static async Task CreateAsync(Workout item)
{
try
{
var json = JsonConvert.SerializeObject(item);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await Client._httpClient.PostAsync(Client._url + $"Workout", data);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
Код: Выделить всё
// Server-side endpoint in ASP.NET Web API controller
[HttpPost]
public async Task Create([FromBody]Workout item)
{
await _workoutContext.CreateAsync(item);
}
Каковы могут быть возможные причины этой проблемы? и как я могу устранить неполадку и решить ее? Любые идеи или предложения будут с благодарностью приняты. Если информации недостаточно, вот мой гитхаб https://github.com/danchuu/Muscles_AppDR. Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/782 ... nd-asp-net