使用 Entity Framework Core 和 ASP.NET Web API 将锻炼数据保存到数据库时遇到问题

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

我在尝试使用 Entity Framework Core 和 ASP.NET Web API 将锻炼数据保存到数据库时遇到困难。我有一个

Workout
类,定义了
WorkoutId
ExerciseTypeGroups
CreatorId
Creator
Status
等属性。
ExerciseTypeGroups
属性是
ExerciseTypeGroup
对象的列表。

我在我的

CreateAsync
中实现了
dbContext
方法,将
Workout
对象添加到数据库并使用
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<ExerciseTypeGroup>(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<ExerciseTypeGroup> ExerciseTypeGroups { get; set; }
    public int CreatorId { get; set; }
    public User Creator { get; set; }
    public Status Status { get; set; }

    public Workout()
    {
        ExerciseTypeGroups = new List<ExerciseTypeGroup>();
    }

    public Workout(User user)
    {
        Status = Status.Waiting;
        Creator = user;
        ExerciseTypeGroups = new List<ExerciseTypeGroup>();
    }
}
// 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);
}

尽管实现了这些方法,我还是遇到了锻炼数据未保存到数据库的问题。我已经验证客户端和服务器端代码执行时没有错误,但数据未保留在数据库中。

导致此问题的可能原因是什么?如何排除和解决?任何见解或建议将不胜感激。如果没有足够的信息这里是我的githubhttps://github.com/danchuu/Muscles_AppDR。谢谢你。

c# asp.net-web-api entity-framework-core
1个回答
0
投票

问题是我将 null 赋予数据库中的不可空列。

© www.soinside.com 2019 - 2024. All rights reserved.