Сохранение входных данных из DataGrid в базу данныхC#

Место общения программистов C#
Anonymous
Сохранение входных данных из DataGrid в базу данных

Сообщение Anonymous »

У меня возникли проблемы с сохранением входных данных из DataGrid в мою базу данных.
У меня есть DataGrid, который имеет 6 столбцов: IName, QTY, Описание , объем, единица измерения и стоимость.
Существует кнопка, которая позволяет пользователю добавлять дополнительные строки, чтобы они могли добавлять больше ингредиентов.
Затем я проверяю, существует ли ингредиент, выполнив поиск IName в базе данных. Если он существует, извлекается IngredientID, но если он не существует, я сохраняю его как новый ингредиент, который сохраняет IName, описание, объем, единицу измерения и стоимость (все, кроме QTY) в tblIngredients .
Это происходит со всеми ингредиентами, возвращающими IngredientID, затем они сохраняются в tblRecipe, который имеет столбцы IngredientID и QTY. code>.
Вновь сгенерированные RecipeID (которые автоматически генерируются при добавлении IngredientID и QTY) затем сохраняются (разделенные запятая, если их больше одного) с оставшимися столбцами из текстового поля.
Ниже приведены три моих класса модели: Ингредиент, Рецепт и Еда, модель представления ингредиентов, а также внешний интерфейс (xaml) и внутренний код (xaml.cs) для одного приема пищи (интерфейс).

Код: Выделить всё

public class IngredientsModel
{
public int IngredientID { get; set; }

public string IName { get; set; }
public string Description { get; set; }
public int Volume { get; set; }
public string Unit { get; set; }
public int Cost { get; set; }

public IngredientsModel()
{
}
}

public class RecipeModel
{
public int RecipeID { get; set; }
public int IngredientID { get; set; }
public int QTY { get; set; }

public RecipeModel()
{
}
}

internal class MealModel
{
public int MealID { get; set; }
public string MName { get; set; }
public string Cuisine { get; set; }
public int PrepTime { get; set; }
public int CookTime { get; set; }
public int Servings { get; set; }
public int UserID { get; set; }
public int RecipeID { get; set; }

public DateTime Date { get; set; }
public string Keywords { get; set; }
public object Image { get; set; }

public MealModel()
{
}
}

public class IngredientViewModel
{
public List IngredientsData { get; set; }
public List IngredientsModels { get; set; }

public IngredientViewModel()
{
IngredientsData = new List();
IngredientsModels = new List();
}

public void AddIngredient()
{
IngredientsData.Add(new IngredientsData()); // Add a new empty IngredientData object
}
}

public partial class SingleMeal : Window
{
private DBConn dbConn = new DBConn();
private string imagePath = "";
private IngredientViewModel viewModel;

public string ingredientName = "";
public string ingredientDescription = "";
public string ingredientVolume = "";
public string ingredientUnit = "";
public string ingredientCost = "";

// SQL Connection Script
private static string SQLConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="
+ System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
+ "\\DAL\\YourMealsDB.mdf;" + "Integrated Security=True";

// New SQL Connection
private SqlConnection connString = new SqlConnection(SQLConnectionString);

public SingleMeal()
{
InitializeComponent();
viewModel = new IngredientViewModel();
dataGrid.DataContext = viewModel;
dataGrid.SelectionChanged += DataGrid_SelectionChanged;
}

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
IngredientsData selectedIngredientsData = (IngredientsData)dataGrid.SelectedItem;

if (selectedIngredientsData != null)
{
ingredientName = selectedIngredientsData.IName;
ingredientDescription = selectedIngredientsData.Description;
ingredientVolume = selectedIngredientsData.Volume.ToString();
ingredientUnit = selectedIngredientsData.Unit.ToString();
ingredientCost = selectedIngredientsData.Cost.ToString();
}
}

public class IngredientsData
{
public string IName { get; set; }
public int QTY { get; set; }
public string Description { get; set; }
public int Volume { get; set; }
public string Unit { get; set; }
public int Cost { get; set;  }
}

private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtName.Text) ||
string.IsNullOrEmpty(txtCuisine.Text) ||
string.IsNullOrEmpty(txtPrepTime.Text) ||
string.IsNullOrEmpty(txtCookTime.Text) ||
string.IsNullOrEmpty(txtServes.Text) ||
string.IsNullOrEmpty(txtKeywords.Text) ||
string.IsNullOrEmpty(imagePath) ||
!viewModel.IngredientsData.Any())
{
MessageBox.Show("Please fill in all fields and add at least one ingredient.");
return;
}

// Save Meal data
int recipeID = SaveIngredientsAndGetRecipeID();
SaveMeal(recipeID);
}

private int SaveIngredientsAndGetRecipeID()
{
int recipeID = 0;

foreach (IngredientsData ingredientData in viewModel.IngredientsData)
{
int ingredientID = GetOrSaveIngredientID(ingredientData);

// Update the existing recipe record with IngredientID and Qty
RecipeModel recipe = new RecipeModel
{
IngredientID = ingredientID,
QTY = ingredientData.QTY
};
dbConn.WriteToRecipeTable(recipe);
}

recipeID = GetGeneratedID("tblRecipe");

return recipeID;
}

private int GetOrSaveIngredientID(IngredientsData ingredientData)
{
// Check if ingredient exists
string query = "SELECT IngredientID FROM tblIngredients WHERE IName = @IName";
int ingredientID = -1;

using (var connection = new SqlConnection(SQLConnectionString))
{
connection.Open();

using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@IName", ingredientData.IName ?? "" );

var result = command.ExecuteScalar();

if (result != null)
{
ingredientID = (int)result;
}
}
}

// If exists, return the existing IngredientID
if (ingredientID != -1)
{
return ingredientID;
}

// If not, save to Ingredient table and return the generated IngredientID
IngredientsModel ingredientToSave = new IngredientsModel
{
IName = ingredientData.IName,
Description = ingredientData.Description,
Volume = ingredientData.Volume,
Unit = ingredientData.Unit,
Cost = ingredientData.Cost
// ...  set other properties as needed ...
};

// Pass the IngredientsModel object to WriteToIngredientTable
dbConn.WriteToIngredientTable(ingredientToSave);

ingredientID = GetGeneratedID("tblIngredients");

return ingredientID;
}

// Helper method to retrieve generated IDs
private int GetGeneratedID(string tableName)
{
string query = $"SELECT IDENT_CURRENT('{tableName}')";
int generatedID = 0;

using (var connection = new SqlConnection(SQLConnectionString))
{
connection.Open();

using (var command = new SqlCommand(query, connection))
{
var result = command.ExecuteScalar();

if (result != null)
{
generatedID = (int)Math.Floor((decimal)result);
}
}
}

return generatedID;
}

private void SaveMeal(int recipeID)
{
MealModel meal = new MealModel
{
MName = txtName.Text,
Cuisine = txtCuisine.Text,
PrepTime = int.Parse(txtPrepTime.Text),
CookTime = int.Parse(txtCookTime.Text),
Servings = int.Parse(txtServes.Text),
UserID = 100001, // Replace with actual UserID
RecipeID = recipeID,
Date = DateTime.Now,
Keywords = txtKeywords.Text,
Image = imagePath
};
dbConn.WriteToMealTable(meal);
}

private void btnUploadImage_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();

if (openFileDialog.ShowDialog() == true)
{
imagePath = openFileDialog.FileName;
btnUploadImage.Background = new ImageBrush(new BitmapImage(new Uri(imagePath)));
}
}

private void btnExit_Click(object sender, RoutedEventArgs e)
{
DisplayTest displayTest = new DisplayTest();
displayTest.Show();
this.Close();
}

private void btnAddIngredient_Click(object sender, RoutedEventArgs e)
{
((IngredientViewModel)dataGrid.DataContext).AddIngredient();
}

Код: Выделить всё

XAML view:
```
Я пытался сохранить определенные входные данные в IngredientsData, но мне не удалось получить все строки из таблицы данных и сохранить их со всеми правильными идентификаторами (

Код: Выделить всё

IngredientID, RecipeID
).
Любая помощь приветствуется.

Подробнее здесь: https://stackoverflow.com/questions/783 ... a-database

Вернуться в «C#»