简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM