Как сделать так чтобы одна таблица создавалась на основе двух предыдущих?

263
07 марта 2018, 04:51

Привет!Я разрабатываю для себя приложение на С# с использованием Entity Framework и у меня начало получатся добавлять и выводить данные с базы но мне нужно сделать так чтобы в таблице RecipeIngredient сразу после добавления рецепта добавлялись ингредиенты к нему в виде Id этого ингредиента. Вот так сейчас выглядит модель моей бд. Продукты которые нужны для рецепта я храню в List-масиве List<string> productsAddList = new List<string>();Мне кажется при добавлении можно будет его перебирать в цикле и сопоставлять данные в RecipeIngredient.RecipeIngredient я создал потому что мне нужно будет сделать потом поиск рецептов по продуктам.

   using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
    public partial class PlusRecepies : Form
    {
        int x = 0;
        List<string> productsAddList = new List<string>();
        public PlusRecepies()
        {
            InitializeComponent();
        }
        private void PlusToFlp_Click(object sender, EventArgs e)
        {
            var label1 = new Label();
            flowLayoutPanel2.Controls.Add(label1);
            label1.Text = ProductPlus.Text;
            productsAddList.Add(ProductPlus.Text);
            }

        private void AddRecepieToDB_Click(object sender, EventArgs e)
        {
            Db1Context context = new Db1Context();
            Recipe recipe = new Recipe
            {
                Instructions = RecepiePRText.Text,
                Name = NameRecipe.Text,
                Prop_Time = Convert.ToInt32(PropTime.Text)
            };

            for (int i = 0; i < productsAddList.Count; i++)
            {
                Ingredients ingredient = new Ingredients
                {
                    Name = productsAddList[i]
                };
                context.Ingredients.Add(ingredient);
                recipe.RecipeIngredient.Add(ingredient);
            }

            context.Recipe.Add(recipe);
            context.SaveChanges();
        }


    }
}

Ingredients.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1
{
    using System;
    using System.Collections.Generic;
    public partial class Ingredients
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Ingredients()
        {
            this.RecipeIngredient = new HashSet<RecipeIngredient>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RecipeIngredient> RecipeIngredient { get; set; }
    }
}

Recipe.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1
{
    using System;
    using System.Collections.Generic;
    public partial class Recipe
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Recipe()
        {
            this.RecipeIngredient = new HashSet<RecipeIngredient>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> Prop_Time { get; set; }
        public string Instructions { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RecipeIngredient> RecipeIngredient { get; set; }
    }
}

RecipeIngredients.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1
{
    using System;
    using System.Collections.Generic;
    public partial class RecipeIngredient
    {
        public int Id { get; set; }
        public int RecipeId { get; set; }
        public int IngredientId { get; set; }
        public virtual Ingredients Ingredients { get; set; }
        public virtual Recipe Recipe { get; set; }
    }
}

READ ALSO
Console Application C#

Console Application C#

Как задать минимально возможный размер окна консоли, меньше которого пользователь не сможет её уменьшить?! Спасибо за ответ ;)

221
Нужно узнать размер папки

Нужно узнать размер папки

последовательность такая, проверяем размер каталога, запоминаем, через некоторое время снова проверяем, сравниваем и по результату что то делаем

187