Ho le seguenti classi:
public class GSProject
{
public int Id { get; set; }
public ICollection<GSPoint> Points { get; set; }
public ICollection<GSPlanarSurface> PlanarSurfaces { get; set; }
}
public class GSPoint
{
public int Id { get; set; }
public int? PlanarSurfaceId { get; set; }
public GSPlanarSurface PlanarSurface { get; set; }
}
public class GSPlanarSurface
{
public int Id { get; set; }
public ICollection<GSPoint> Points { get; set; }
public int? PxyId { get; set; }
public GSPoint Pxy { get; set; }
public int? PyId { get; set; }
public GSPoint Py { get; set; }
}
e contenuto della classe di contesto (OnModelCreating () correlato):
modelBuilder.Entity<GSPlanarSurface>()
.HasMany(e => e.Points)
.WithOne(e => e.PlanarSurface)
.HasForeignKey(e => e.PlanarSurfaceId);
Quindi ho creato la migrazione ef e il contenuto del file .cs relativo alla migrazione è:
migrationBuilder.CreateTable(
name: "GSPoints",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
PlanarSurfaceId = table.Column<int>(nullable: true),
},
constraints: table =>
{
table.PrimaryKey("PK_GSPoints", x => x.Id);
table.ForeignKey(
name: "FK_GSPoints_GSPlanarSurfaces_PlanarSurfaceId",
column: x => x.PlanarSurfaceId,
principalTable: "GSPlanarSurfaces",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
Errore:
{System.Data.SqlClient.SqlException (0x80131904): l'istruzione MERGE era in conflitto con il vincolo FOREIGN KEY "FK_GSPoints_GSPlanarSurfaces_PlanarSurfaceId". Il conflitto si è verificato nel database "GSTDb", nella tabella "dbo.GSPlanarSurfaces", nella colonna "Id".
appare se provo a chiamare:
context.Set<GSProject>().Add(entity);
await context.SaveChangesAsync();
entity è un'istanza di GSProject con alcuni GSPoints e senza alcuna istanza di GSPlanarSurface (entity.PlanarSurfaces Count = 0)
MODIFICARE:
ed ecco uno script generato automaticamente in t-sql per la chiave:
USE [GSTDb]
GO
ALTER TABLE [dbo].[GSPoints] WITH CHECK ADD CONSTRAINT [FK_GSPoints_GSPlanarSurfaces_PlanarSurfaceId] FOREIGN KEY([PlanarSurfaceId])
REFERENCES [dbo].[GSPlanarSurfaces] ([Id])
GO
ALTER TABLE [dbo].[GSPoints] CHECK CONSTRAINT [FK_GSPoints_GSPlanarSurfaces_PlanarSurfaceId]
GO
Ho eseguito un semplice script tsql:
insert into GSProjects ([Description] ,[Name]) values ('d1', 'proj1')
insert into GSPoints([Number], [IsSlave] ,[X], [Y], [Z]) values (0, 0, 0, 0, 0)
insert into GSPoints([GSProjectId], [Number], [IsSlave] ,[X], [Y], [Z]) values (5, 0, 0, 0, 0, 0)
e non ci sono stati problemi con l'inserimento. Primo GSPoint ha GSProjectId impostato su null, il secondo GSPoint ha GSProjectId impostato su un valore non nullo (5 qui). Entrambi hanno GSPlanarSurfaceId impostato su null ed entrambi sono stati inseriti correttamente.
La risposta non è correlata a EntityFramework. Nel mio caso PlanarSurfaceId è stato impostato di default su 0. L'ho cambiato in null e funziona.