Artem
Artem

Reputation: 1050

Adding new members to a DbSet<Class> in ASP.NET MVC 4

Here is my scenario: I have a class called Order, which consists of basic information that should be saved in the database after that an order has been made.

In MyPoject.Infrastructure I use following code:

public class ProductDb : DbContext, IProductDataSource
{

    public ProductDb()
        : base("DefaultConnection")
    {
    }


    public DbSet<Order> Orders { get; set; }


    IQueryable<Order> IProductDataSource.Orders
    {
        get
        {
            return Orders;
        }
        set
        {
            Orders = (DbSet<Order>)value;
        }
    }
}

In the Controller, I add this:

    private IProductDataSource _db = new ProductDb();

    public UserController(IProductDataSource db)
    {
        _db = db;
    }

Later on, in the ActionResult, where I want to add data to the order I use following:

var orders = _db.Orders;
var order = new Order();

//add some data to the order variable

_db.Orders.AsEnumerable().Concat(new[] { order });
_db.Save();

However, this does not appear to work. The problem I face is how it is possible to add new items to Order in the database.

EDIT: IProductDataSource contains following code

    public interface IProductDataSource
{

    IQueryable<UserProfile> UserProfiles { get; set; }

    IQueryable<Order> Orders { get; set; }


    void Save();
    void Add();
    //void Add();
}

Upvotes: 0

Views: 3340

Answers (2)

Claies
Claies

Reputation: 22323

Looking at your code, it appears you are using an Interface to create an IQueryable<Order>, presumably to not expose the rest of your systems to Entity Framework. However, an IQueryable<T> is just a special version of IEnumerable<T>, it still does not have access to Entity Framework features.

If you don't mind exposing your DBset<Order>, it is much easier to work that way since DBSet<T> has full support of Entity Framework behind it and supports add, delete, etc.

However, if you don't want to work with a DBSet<T> for some reason, you will need to create your own Add method which takes in your new Order, creates a temporary DBSet<Order>, adds the Order to the DBSet, then saves the changes. You cannot Add directly to the IQueryable<Order>.

Upvotes: 3

Matt Millican
Matt Millican

Reputation: 4054

You need to do this:

var orders = _db.Orders;
var order = new Order();

//add some data to the order variable

_db.Orders.Add(order); // order is your new Order
_db.Save();

Upvotes: 1

Related Questions