简体   繁体   English

如何在带有自定义多对多关联的Entity Framework中插入?

[英]How to insert in Entity Framework with custom many-to-many association?

I created all of my entities based on a tutorial, and it seems to be working, at least my database tables are created but I just can't figure out how to insert any new data with the following setup: 我根据一个教程创建了所有实体,并且似乎可以正常工作,至少创建了我的数据库表,但是我无法弄清楚如何使用以下设置插入任何新数据:

My model classes: 我的模型课:

public class Coffee 
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CoffeeId { get; set; }

        [MaxLength(100)]
        [Required]
        public string Name { get; set; }

        [MaxLength(100)]
        [Required]
        public string ImagePath { get; set; }

        [MaxLength(100)]
        [Required]
        public string Price { get; set; }

        [MaxLength(400)]
        [Required]
        public string Description { get; set; }

        public virtual ICollection<IngredientCoffees> Ingredients { get; set; }
}

public class Ingredient 
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int IngredientId { get; set; }

        [MaxLength(100)]
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
        public string Name { get; set; }

        [Required]
        public int Amount { get; set; }

        [Required]
        [StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 1)]
        public string Unit { get; set; }

        public virtual ICollection<IngredientCoffees> Coffees { get; set; }
}

public class IngredientCoffees 
{
        public int Coffee_Id { get; set; }
        public int Ingredient_Id { get; set; }

        public virtual Coffee Coffee { get; set; }
        public virtual Ingredient Ingredient { get; set; }

        public int amount { get; set; }
}

And in the OnModelCreating method of my DbContext class, I have this: 在我的DbContext类的OnModelCreating方法中,我有以下内容:

builder.Entity<IngredientCoffees>()
                .HasKey(ic => new { ic.Coffee_Id, ic.Ingredient_Id });

builder.Entity<IngredientCoffees>()
                .HasRequired(ic => ic.Coffee)
                .WithMany(ic => ic.Ingredients)
                .HasForeignKey(ic => ic.Coffee_Id);

builder.Entity<IngredientCoffees>()
                .HasRequired(ic => ic.Ingredient)
                .WithMany(ic => ic.Coffees)
                .HasForeignKey(ic => ic.Ingredient_Id);

All of these will result in the following database structure: 所有这些将导致以下数据库结构:

my tables 我的桌子

How do I insert a new Coffee with already existing ingredients in the database, so they get joined in my IngredientCoffees table, where I also want to set them the "amount" column? 如何在数据库中插入具有现有成分的新Coffee ,以使它们加入我的IngredientCoffees表中,在此我还想将其设置为“金额”列?

You can use array or List 您可以使用数组或列表

if (context.Coffee .Any())
        {
            return;   // DB has been seeded
        }
 var coffees = new Coffee []
        {
            new Coffee { Name = "Coffee name",   ImagePath = "/[your path]",
                Price = "[price]", Description ="description" },
             new Coffee {......................}

         }

       foreach (Coffee coffee in coffees)
        {
            context.Coffee.Add(coffee);
        }
        context.SaveChanges();

The same you can do with the Ingredient in the same file 您可以对同一文件中的成分执行相同操作

var ingredients= new Ingredient []
        {
            new Ingredient { Name = "Ingredient name",  
                 Amount = [your amount], Unit = "[ your unit ]"  },
             new Ingredient {......................}

         }

       foreach (Ingredient ingredient in ingredients)
        {
            context.Ingredient.Add(ingredient);
        }
        context.SaveChanges();

I already found a solution for the problem I had! 我已经找到了解决问题的方法! It seems EF treats many to many relations where you want to have custom column (in my case amount ) a little differently, so you have to do more manual work, at least that's what I read. 这似乎EF治疗许多的地方,你想拥有(在我的情况下,自定义列许多关系amount )略有不同,所以你必须做更多的体力劳动,至少这是我读。 This is the way I did it: 这是我做到的方式:

//create a new coffee
var americano = new Coffee 
            {
                Name = "Americano",
                ImagePath = "https://imgurl.jpg",
                Price ="5",
                Description = "Americano is a type of coffee drink prepared by.."
            };

//select existing ingredient from the db
            var coffee_powder = context.Ingredients.Where(i => i.Name == "coffee powder")
                            .SingleOrDefault();

//if found, create a new IngredientCoffee
            if (coffee_powder != null) {
                var ingredientCoffees = new IngredientCoffees { Coffee = americano, Ingredient = coffee_powder, amount = 8 };

//add it, with this your new coffee will be created automatically too
                context.IngredientCoffees.Add(ingredientCoffees);


                context.SaveChanges();

            }

It will create your new row, and the correct ids in the associated table. 它将创建您的新行以及关联表中的正确ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM