mche
mche

Reputation: 646

Entity Framework - SaveChanges() on my DbContext is not appearing in my intellisense

Hopefully I have things set up correctly, and I have implemented this in the past in .net core but my current environment is .net 4.5x. EF version 6.1.x.

My problem is, I am trying to create an Add method, that will class the DbContext's Add method. However, when I try and call the SaveChanges() from the DbContext, intellisense tells me it doesn't exists. This pattern worked when I had used EF in .net core and online references tell me this is how it should work as well?

Additionally, I came across another stackoverflow post mentioning how the System.Data.Entity using statement needed to be added - this is included but still doesn't work.

The code:

public class ARepository : DbContext
{
    public RegRepCommodityRepository()
        : base("WhateverConnectionString")
    {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<ARepository>(null);
        modelBuilder.Entity<SomeClass>().ToTable("dbo.SomeClass");
        base.OnModelCreating(modelBuilder);
    }

    private DbSet<SomeClass> MyContext { get; set; }

    public IEnumerable<SomeClass> SelectEverything()
    {
        return MyContext.ToList();
    }

    public void Add(MyClass addThisClass)
    {
        MyContext.Add(addThisClass);
        MyContext.SaveChanges(); // Intellisense tells me that SaveChanges does not exists
    }
}

* EDIT *

just call this.SaveChanges().

Upvotes: 0

Views: 687

Answers (4)

Sandeep Suthar
Sandeep Suthar

Reputation: 57

SaveChanges() is a method of the DbContext and not of the DbSet. DbSet represents one table, the DbContext could represents your db or a part of it. it seems also that you are trying to implement repository pattern in your dbContext class that it's not correct, read it for more detail Click Here

Upvotes: 0

hitesh panwar
hitesh panwar

Reputation: 40

Try dis instantobj.SaveChanges();

Upvotes: 0

Mohammed Suez
Mohammed Suez

Reputation: 159

SaveChanges() is not static method, you can't call it without instantiating an object of your DbContext class, You can call this instead.

this.SaveChanges();

Upvotes: 1

Embri
Embri

Reputation: 622

SaveChanges() is a method of the DbContext and not of the DbSet. DbSet represents one table, the DbContext could represents your db or a part of it. it seems also that you are trying to implement repository pattern in your dbContext class that it's not correct, i suggest you to read this.

Upvotes: 2

Related Questions