Reputation: 646
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
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
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
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