I am doing a project and in that I two table agent and user. The user table contains a foreign key called agentid which takes the value from the id of the agent table. so here I need to delete an agent in the agent table and at the same time it must effect to the user table and must delete the row in the user table that having the same id of the agent that was deleted. eg, suppose if i deleted agent 10 from agent table, all the details in the id 10 must be deleted along with that the agentid with 10 in the user table must also be deleted. when I simply delete an agent in agent table, it generates an error that
The DELETE statement conflicted with the REFERENCE constraint
I dont know how to solve my problem and my code is
Controller
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
AgentMaster agentMaster = await db.AgentMasters.FindAsync(id);
db.AgentMasters.Remove(agentMaster);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
model
public partial class AgentMaster
{
public AgentMaster()
{
this.Users = new HashSet<User>();
}
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<User> Users { get; set; }
}
DbContext
public NewEntities()
: base("name=NewEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
modelBuilder.Entity<AgentMaster>()
.HasOptional(c => c.Users)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
This is my controller part, when I tried with join the table and delete the record it always shows the same error . Can anyone please help me to find a solution for my problem ?????