How to add List of Ingredients to Recipe ASP.NET Core MVC

.net-core entity-framework-core


I'm working on .NET Core 3.1.1. I have problem with extending my Recipe class.

This is my class stored in the database:

public class Recipe
    public int Id { get; set; }
    public string Name { get; set; }
    public string Ingredients { get; set; }
    public int PreparationTime { get; set; }
    public string Description { get; set; }
    public DateTime DateAdded { get; set; }
    public ICollection<RecipePhoto> RecipePhotos {get; set;}
    public User User { get; set; }
    public int UserId { get; set; }

I would like to change the Ingredients string property to a list of ingredients.

I've tried to change :

public string Ingredients { get; set; } 


public ICollection<string> Ingredients { get; set; }

Then add the new migration but in response I get:

The property 'Recipe.Ingredients' could not be mapped, because it is of type 'ICollection' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

4/4/2020 11:14:04 PM

Accepted Answer

Entity Framework does not support collections of primitive types. You can either create an entity (which will be saved to a different table) or do some string processing to save your list as a string and populate the list after the entity is materialized.

12/20/2013 9:12:30 PM

Popular Answer

EF Core 2.1+ :


public string[] Strings { get; set; }


            .Property(e => e.Strings)
                v => string.Join(',', v),
                v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow