ASP.NET MVC4:IQueryable的不包含定义“添加” [英] ASP.NET MVC4: IQueryable does not contain a definition for 'Add'

查看:319
本文介绍了ASP.NET MVC4:IQueryable的不包含定义“添加”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个MVC新闻系统。我开始使用这是用来创建雇员的部门一个pluralsight教程。我改变了主意,适合我自己的目的,改变了部门类别和员工newspost。这一切都优秀作品,但是现在我想删除的类别,因为我不需要为我的新闻系统类。但我可以使用的EntityFramework当我这样做不添加到数据库中。

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

然后我想用它的控制器到newspost添加到数据库:

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

但是,这是在ADD失败消息:System.Linq.IQueryable不包含添加的定义,并没有扩展方法'添加'接受一个类型的第一个参数'System.Linq的.IQueryable'可以找到(是否缺少using指令或程序集引用?)

现在的错误说其因使用IQueryable的,但我不知道怎么回事做到这一点。

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

你们能帮忙吗?

感谢。

推荐答案

如果你不介意通过你的接口暴露DbSet(有些人不喜欢ORM出血到应用程序),你应该能够做到以下内容:

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

这篇关于ASP.NET MVC4:IQueryable的不包含定义“添加”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆