我正在尝试为我管理的数据库创建一行。 我试图构建一个代码作为示例来检查它是否正常工作,但它没有更新数据库:
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
我是否使用异步方法无效,EntityState.Added也是如此。 如何保存更改?
private async Task<List<tblPolicy>> LoadPolicy()
{
return await Task.Run(() => mdbe.tblPolicies.ToList());
}
mdbe定义:
EntryDBEntities mdbe = new EntryDBEntities();
POCO类的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; }
}
答案 0 :(得分:1)
您应该删除代码中不必要的/绝对的部分并创建一个MVE(Minimal, Complete, and Verifiable example)进行测试。
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
}
上面的片段应该向底层数据库添加一个新的tblPolicy
,这是完成此操作所需的最低代码。
如果“不起作用”,请提供以下信息:
tblPolicy