I’m trying to use context as partially as possible because I want my software to be used by multiple users and I already had problems with contexts integration… so what I’m doing is calling the context like that:
entityManager = new EntityManager();
IEnumerable<customers_question_set> customersQuestionSets =
entityManager.GetTradersCustomersQuestionSets(trader.id).ToArray<customers_question_set>();
entityManager = null;
This way, I believe, not only I’m closing everything with =null but also detaching the objects from the context by .ToArray().
But now I’m trying to add new item to the database and I’ve met a problem. This are my actions:
private void button1_Click(object sender, EventArgs e)
{
trader trader = new trader();
trader.companies.Add(parent.GetCompany());
trader.login = textBox1.Text;
trader.password_hash = Hasher.ToSha256Hash(textBox2.Text);
EntityManager entityManager = new EntityManager();
entityManager.SaveTrader(trader);
entityManager = null;
this.RefreshLists();
}
public class EntityManager
{
private mentor11Entities Mentor11Entities = new mentor11Entities();
private mentor11Entities GetMentor11()
{
return this.Mentor11Entities;
}
public void SaveTrader(trader trader)
{
GetMentor11().traders.AddObject(trader);
GetMentor11().AcceptAllChanges();
GetMentor11().SaveChanges();
}
[...]
}
The error happens at GetMentor11().traders.AddObject(trader) – how to detach it if it’s a new member I didn’t even take from anywhere?
As there are a lot of people having problem with this and in the Internet there is no simple (for beginners as I am) explanation I could find… I will share how I resolve my problem.
I’ve made EntityManager static after all.
I discovered “StoreWins” refresh type (It’s making sure that the output is always as in the server)
And so it looks like this and working fine: