Does not contain a definition for "Add" c# entity-framework


I'm trying to create something similar to that in the this thread, but I'm running into an error:

'System.Collections.Generic.IEnumerable' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)

This is my code:

public ActionResult Create(ANIME anime)
    var db = new MainDatabaseEntities();
    var newanime = new ANIME
        ID_AN = anime.ID_AN,
        TITLE_OR = anime.TITLE_OR,
        TITLE_EN = anime.TITLE_EN,
        GENRES = new List<GENRES>()

    foreach (var selectedAnime in anime.GENRES.Where(c => c.isSelected))
        var genre = new GENRES { ID_GE = selectedAnime.ID_GE };
        newanime.GENRES.Add(genre); <--- this is the error line

    return RedirectToAction("Index");


public partial class ANIME
    public int ID_AN { get; set; }
    public string TITLE_OR { get; set; }
    public string TITLE_EN { get; set; }

    public virtual IEnumerable<GENRES> GENRES { get; set; }


public partial class GENRES
    public int ID_GE { get; set; }
    public string GENRE { get; set; }
    public bool isSelected { get; set; }
    public virtual ICollection<ANIME> ANIME { get; set; }

The line contains the error.newanime.GENRES.Add(genre) in HttpPost I includedusing System.Linq to every model and controller, but it makes no difference. Any suggestions on how to fix this?


A new fault appeared after this was fixed. I believe it has nothing to do with the previous one, but I don't want to spam threads.

Message of error:

The entity or complex type 'MainDatabaseModel.GENRES' cannot be constructed in a LINQ to Entities query.

Associated code:

public ActionResult Create()
    var db = new MainDatabaseEntities();
    var viewModel = new ANIME
        GENRES = db.GENRES.Select(c => new GENRES
            ID_GE = c.ID_GE,
            GENRE = c.GENRE,
            isSelected = false
    return View(viewModel);       
5/23/2017 12:26:27 PM

Accepted Answer

12/2/2013 11:21:58 AM

Popular Answer

You are initializing an IEnumerable property that you have with a List. The IEnumerable interface is implemented by the List class.

When you invoke a phrase like this:

IEnumerable myList = new List<MyType>();

You claim that you desire for your thing the characteristics of theIEnumerable that are additionally inherited in theList class. Specifically, the approachAdd is simply a method of the List class, not the IEnumerable interface, and you have that exception.

The type of your property must then be changed fromIEnumerable<YourType> to IList<YourType> (More details on IList here). This is how the exception toAdd thrown by the procedure.

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