Reputation: 11
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
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:
tblPolicy
Upvotes: 1