我正在尝试制作与 this 中相同的东西线程,但出现错误:
'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?)
这是我的代码:
[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");
}
动漫:
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; }
}
错误在 HttpPost
中的 newanime.GENRES.Add(genre)
行中。我将 using System.Linq
添加到所有模型和 Controller ,但没有帮助。有什么解决办法吗?
编辑:
修复此问题后,出现了新错误。我认为它与上述内容无关,但我不想向不必要的线程发送垃圾邮件。
错误信息:
The entity or complex type 'MainDatabaseModel.GENRES' cannot be constructed in a LINQ to Entities query.
相关代码:
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);
}
最佳答案
您有一个用列表初始化的 IEnumerable 属性。 List 类实现了 IEnumerable 接口(interface)。
当你调用这样的东西时:
IEnumerable myList = new List<MyType>();
你是说你想要你的对象具有 IEnumerable
的特征接口(interface)也继承自 List
类(class)。在这种情况下,方法 Add
不是 IEnumerable 接口(interface)的一部分,因为它只是 List 类的一个方法,而且你有那个异常(exception)。
然后您必须更改属性的类型,从 IEnumerable<YourType>
至 IList<YourType>
(有关 IList here 的更多信息)。如果这样做,关于 Add
的异常方法不会被抛出。
关于c# - 不包含 "Add"的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20327034/