I'm trying to make the same thing like in this thread, but I'm getting 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?)
Here is my code:
[HttpPost]
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 };
db.GENRES.Attach(genre);
newanime.GENRES.Add(genre); <--- this is the error line
}
db.ANIME.Add(newanime);
db.SaveChanges();
return RedirectToAction("Index");
}
ANIME:
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; }
}
GENRES:
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 error is in the line newanime.GENRES.Add(genre)
in HttpPost
. I added using System.Linq
to all models and controllers but it doesn't help. Any ideas how to resolve this?
EDIT:
After repairing this a new error arrived. I think it's not related to above one but I don't want to spam unnecessary threads.
Error message:
The entity or complex type 'MainDatabaseModel.GENRES' cannot be constructed in a LINQ to Entities query.
Related 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
}).ToList()
};
return View(viewModel);
}
.Add
method inLinq
either;IEnumerable
s cannot be modified.IEnumerable
for a view model. You are using your Entity Framework entities as view models (about which I warned you on an earlier question), you cannot apply that logic as models requireICollection
for navigation properties that are one-to-many relations. Just changeIEnumerable<T>
toICollection<T>
.