ASP.NET MVC4: IQueryable does not contain a definition for 'Add'

牧云@^-^@ 提交于 2019-12-13 00:45:16

问题


I have tried to make an MVC news system. I started by the use a pluralsight tutorial which was used to create a department with employees. I changed the idea to fit my own purposes, changing the departments to "category" and employees to "newspost". This all works out fine, but now I want to remove the categories, since I don't need categories for my news system. But I can't add to the database using entityframework when I do this.

I have an interface for the datasource that looks like this:

INewMvcSiteDataSource

public interface INewMvcSiteDataSource
{
    IQueryable<NewsPost> NewsPosts { get; }

    void Save();
}

This is inherited by my DB Context class:

NewMvcSiteDb

public class NewsMvcSiteDb : DbContext, INewMvcSiteDataSource
{
    public NewsMvcSiteDb() : base("DefaultConnection")
    {
    }

    public DbSet<NewsPost> NewsPosts { get; set; }

    IQueryable<NewsPost> INewMvcSiteDataSource.NewsPosts
    {
        get { return NewsPosts; }
    }

    public void Save()
    {
        SaveChanges();
    }
}

I then want to use it in the controller to add a newspost to the database:

NewsController

var newsPost = new NewsPost()
                    {
                        Subject = newsModel.Subject,
                        Content = newsModel.Content,
                        ImagePath = newsModel.ImagePath
                    };
_db.NewsPosts.Add(newsPost);
_db.Save();

But this is where the ADD fails with the message: 'System.Linq.IQueryable' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Linq.IQueryable' could be found (are you missing a using directive or an assembly reference?)

Now as the error says, its caused by using IQueryable, but I have no idea how else to do it.

Can you guys help?

Thanks.


回答1:


If you don't mind exposing DbSet via your interface (some people don't like the ORM bleeding into the application),you should be able to do the following:

public interface INewMvcSiteDataSource
{
    DbSet<NewsPost> NewsPosts { get; }

    void Save();
} 



public class NewsMvcSiteDb : DbContext, INewMvcSiteDataSource
{
    public NewsMvcSiteDb() : base("DefaultConnection")
    {
    }

    public DbSet<NewsPost> NewsPosts { get; set; }

    public void Save()
    {
        SaveChanges();
    }
}


来源:https://stackoverflow.com/questions/14582805/asp-net-mvc4-iqueryable-does-not-contain-a-definition-for-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!