How to save an object containing a list of objects to database in ASP.NET MVC with EF?

549 Views Asked by At

I know this question exists ( I literally copy pasted it) but its answer is unclear and doesnt work for me I have a model which Ive tried adding to a database, it consist of complex datatypes and lists and the database has stored it totally not the way I intended this is my class im trying to store: ''' `

enter code here
`[Table("Recipes")]
    public class Recipe
    {

    public int Id { get; set; }
    public string Title { get; set; }

    [DisplayName("Descrption")]
    public string Description { get; set; }
    public Tags RTags { get; set; }

    [ForeignKey("Id")]
    public List<Ingredient> Ingredients { get; set; }

    [ForeignKey("Id")]
    public List<Instruction> Instructions { get; set; }
    public string Image { get; set; }
}

'''

this is my class ingredient: '''`

public class Ingredient
    {
        [ForeignKey("recipe Id")]
        public int Id  { get; set; }
        public string Name { get; set; }
        public int Amount { get; set; }

        public MeasurementType MeasurementUnit { get; set; }
    }`
 `

`
''' here is what it is stored like in the db: as you can see in the image it has only saved an object with id, title, description, RTagsid and image

database without lists or complex data

1

There are 1 best solutions below

2
Kiran Joshi On

You can store changes to a child object like following:

using (var context = new MyContext())
{
   ctx.Recipe.Attach(recipe);// Parent
    ctx.Entry(recipe).State = EntityState.Added;  
    ctx.Ingredient.Attach(ingredient);// Child
    ctx.Entry(ingredient).State = EntityState.Added;  // or EntityState.Modified
    ctx.SaveChanges();
}