I'm having a question with Entity Framework
I have a situation in which I want to implement a structure in the database of a chart of accounts, for example: the current active account ID 1.1 is the parent of the account box 1.1.1, is my business rule
Assuming the hypothetical situation I already have the active parent account saved in the bank, and you want to save a child account, example account box.
I created these two methods: one that saves a new account in the bank, and another that queries an account in the bank and returns an IQueriable collection
//Método para salvar uma nova conta
public static void IncuirDB(Conta ObjConta, string IDContaPai)
{
Contexto Db = new Contexto();
var ContaPai = Repositorio.Consultar(IDContaPai, "");
var ContaPaiFirst = ContaPai.FirstOrDefault();
ObjConta.ContaPai = ContaPaiFirst;
Db.Conta.Add(ObjConta);
Db.SaveChanges();
}
//Método para consultar uma conta
public static IQueryable<Conta> Consultar(string _IDConta, string _Nome)
{
Contexto Db = new Contexto();
var Consultar = from c in Db.Conta where c.Codigo == _IDConta select c;
return Consultar;
}
The problem occurs when I try to save my account object, which has a property of type contaPai which is also an object of type account. This object comes from the user interface layer and I just want to include a contapai property in it, before saving it to the database. However I can not because I have had the error below.
ERROR Detail: "Violation of PRIMARY KEY constraint 'PK_dbo.Conta'. Can not insert duplicate key in object 'dbo.Conta' .The duplicate key value is (1.1). \ R \ nThe statement has been terminated."}
NOTE: I am sure that the account I am trying to include does not exist in the database.
Can anyone give me a hand?