【发布时间】:2013-12-18 02:04:41
【问题描述】:
我正在尝试在this 线程中做同样的事情,但我收到了错误:
“System.Collections.Generic.IEnumerable”不包含“Add”的定义,并且找不到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的扩展方法“Add”(您是否缺少using 指令还是程序集引用?)
这是我的代码:
[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,但它没有帮助。任何想法如何解决这个问题?
编辑:
修复此问题后,出现了一个新错误。我认为它与上述无关,但我不想发送不必要的线程。
错误信息:
无法在 LINQ to Entities 查询中构造实体或复杂类型“MainDatabaseModel.GENRES”。
相关代码:
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);
}
【问题讨论】:
-
这篇文章解释了更多你的问题stackoverflow.com/questions/1210295/…
-
@Satpal:
Linq中也没有.Add方法;IEnumerables 无法修改。 -
您链接到的问题将
IEnumerable用于视图模型。您正在使用您的 Entity Framework 实体 作为视图模型(我在之前的问题中警告过您),您不能将该逻辑应用为模型 requireICollectionfor navigation properties that are one-to-many relations。只需将IEnumerable<T>更改为ICollection<T>。 -
如果我可以问,为什么你的属性/类有奇怪的命名约定?在C#中,我们对属性、方法和类型使用Pascal Case,对字段使用camelCase(一般不暴露)
标签: c# asp.net-mvc entity-framework asp.net-mvc-4