Refi
Refi

Reputation: 11

Entity Framework's DBContext doesn't update database

I am trying to create a row for a database which I manage. I have tried to build a code as an example to check if it's working, but it doesn't update the database:

PolicyList = await LoadPolicy(); //Loads Policy List
            tblPolicy tbl = new tblPolicy(); //Creates a new policy entity
            tbl.polID = 5; //Sets ID to 5
            tbl.polName = "Ryder"; //Sets name
            mdbe.tblPolicies.Add(tbl); //Adds to the dbcontext object
            mdbe.Entry(tbl).State = EntityState.Added; //Changes the state to "Added"
            await mdbe.SaveChangesAsync(); //Saves changes

It doesn't work whether I'm using an Asynchronous method or not, and the same goes with the EntityState.Added. How can I save the changes?

private async Task<List<tblPolicy>> LoadPolicy()
    {
        return await Task.Run(() => mdbe.tblPolicies.ToList());
    }

mdbe definition:

    EntryDBEntities mdbe = new EntryDBEntities();

the POCO class of entryDBentities:

public partial class EntryDBEntities : DbContext
{
    public EntryDBEntities()
        : base("name=EntryDBEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<tblEntry> tblEntries { get; set; }
    public virtual DbSet<tblEntryPolicy> tblEntryPolicies { get; set; }
    public virtual DbSet<tblPolicy> tblPolicies { get; set; }
}

Mapping of the entity framework

Upvotes: 0

Views: 516

Answers (1)

Igor
Igor

Reputation: 62213

You should remove the unecessary / extranious parts of your code and create an MVE(Minimal, Complete, and Verifiable example) to test with.

using(EntryDBEntities mdbe = new EntryDBEntities())
{
  // PolicyList = await LoadPolicy(); // do not include this, it has nothing to do with adding a new entity based on the code you have shown
  tblPolicy tbl = new tblPolicy(); //Creates a new policy entity
  tbl.polID = 5; //Sets ID to 5
  tbl.polName = "Ryder"; //Sets name
  mdbe.tblPolicies.Add(tbl); //Adds to the dbcontext object
  await mdbe.SaveChangesAsync(); //Saves changes
}

The above fragment should add a new tblPolicy to the underlying database and is the bare minimum required code to do so.

If this "does not work" please provide the following:

  1. How does it not work? If an Exception is thrown please provide all of the Exception's properties (stacktrace, message, type, and same for inner exceptions).
  2. If you do not see a result please describe how you are checking the store that your entity was not created/added? It could be as simple as you overridding an .mdf file on a local db when you execute your application from VS.
  3. Include the complete mapping for entity tblPolicy

Upvotes: 1

Related Questions