Well, in my project I decided to use some Foreign Keys. And after you end up getting this error:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \" FK_dbo.Setors_dbo.Areas_setorAreas \ ". The conflict occurred in database \" RamalAguia.Models.RamaDb \ ", table \" dbo.Areas \ ", column ' areaID '. \ r \ nThe statement has been terminated. "}
I noticed that in my Table there was a Foreign Key that I was not creating that had no relation to my current project. But so far so good, the problem was that even after updating the database and deleting this FK every time I ran my project it reappeared.
My Models
Sector
public class Setor
{
[Key, Column(Order =1 )]
public int setorID { get; set; }
public string setorName { get; set; }
[ForeignKey("Area"), Column(Order = 3)]
public int areaID { get; set; }
public Area Area { get; set; }
//[ForeignKey("SetorId")]
//public ICollection<RamalModel> RamalModel { get; set; }
}
Table of the Sector model
CREATE TABLE [dbo].[Setors] (
[setorID] INT IDENTITY (1, 1) NOT NULL,
[areaID] INT NOT NULL,
[setorName] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Setors] PRIMARY KEY CLUSTERED ([setorID] ASC),
//Essa linha de baixo cria um FK que eu não peço onde eu não tenho esse "setorAreas"
CONSTRAINT [FK_dbo.Setors_dbo.Areas_setorAreas] FOREIGN KEY ([areaID]) REFERENCES [dbo].[Areas] ([areaID]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Setors_dbo.Areas_areas_areaID] FOREIGN KEY ([areaID]) REFERENCES [dbo].[Areas] ([areaID])
);
GO
CREATE NONCLUSTERED INDEX [IX_areaID]
ON [dbo].[Setors]([areaID] ASC);
Area
public class Area
{
[Key, Column(Order=3)]
public int areaID { get; set; }
public string areaNome { get; set; }
}
Table of the Model Area
CREATE TABLE [dbo].[Areas] (
[areaID] INT IDENTITY (1, 1) NOT NULL,
[areaNome] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Areas] PRIMARY KEY CLUSTERED ([areaID] ASC)
);
Thank you in advance.