不包含“添加”的定义

时间:2013-12-02 11:20:07

标签: c# asp.net-mvc entity-framework asp.net-mvc-4

我正在尝试像this线程那样做同样的事情,但我收到错误:

  

'System.Collections.Generic.IEnumerable'不包含'Add'的定义,也没有扩展方法'Add'接受类型为'System.Collections.Generic.IEnumerable'的第一个参数'(你丢失了吗?) 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");
}

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; }
}

错误位于newanime.GENRES.Add(genre)中的HttpPost行。我向所有模型和控制器添加了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);       
}

4 个答案:

答案 0 :(得分:7)

您有一个IEnumerable属性,您正在使用List进行初始化。 List类实现IEnumerable接口。

当你调用这样的东西时:

IEnumerable myList = new List<MyType>();

您说您希望对象具有IEnumerable接口的功能,这些功能也在List类中继承。在这种情况下,方法Add不是IEnumerable接口的一部分,因为它只是List类的一个方法,并且你有这个例外。

然后,您必须更改您的媒体资源类型,从IEnumerable<YourType>更改为IList<YourType>(有关IList here的更多信息)。通过这种方式,不会抛出关于Add方法的异常。

答案 1 :(得分:5)

试试这个:

public partial class ANIME
{

    public int ID_AN { get; set; }
    public string TITLE_OR { get; set; }
    public string TITLE_EN { get; set; }

    public virtual ICollection<GENRES> GENRES { get; set; } // Use ICollection here
}

答案 2 :(得分:1)

第二个问题的答案是你不能(也不应该)投射到映射的实体上。但是,您可以投影到匿名类型或数据传输对象。

看到这个帖子: The entity cannot be constructed in a LINQ to Entities query

此外,请不要将您的初始问题延伸至未来的全新,未实现的问题。它很难跟上......

答案 3 :(得分:0)

IEnumerable<>只是一系列项目。您无法向其中添加项目,也无法从中删除项目。你可以查询它。

如果您需要添加项目,则需要至少实现ICollection<>界面或IList<>界面的集合。

好消息是你可以使用IEnumerable<>,如下所示

var list = new List<GENRES>();
var newanime = new ANIME
{
    ID_AN = anime.ID_AN,
    TITLE_OR = anime.TITLE_OR,
    TITLE_EN = anime.TITLE_EN,
    GENRES = list
};

list.Add(genre);

但这种可能性有限。离开作用域并松开对本地list变量的引用后,您将无法添加新项目。

相关问题