我在调试时遇到此异常错误
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while saving the entity changes. See the inner exception for details. Inner Exception : SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Projets_Plannings_ID_Projet". The conflict occurred in database "winky", table "dbo.Plannings", column 'ID_Planning'.'
。我查看了现有的解决方案。我不明白如何解决我的案例中的错误。没找到类似的东西。我试过。所以请我感谢任何帮助。这是我的代码和有问题的模型。 PS:我不使用 SSQM。
程序.cs
using Projet.Models;
using Microsoft.EntityFrameworkCore;
using System;
using Projet;
using (ProjetContext context = new ProjetContext())
{
Projets projet = new Projets()
{
ID_Projet = 1,
Nom_Projet = "Cut_Line generator",
Description_Projet = "",
Version_Projet = "41",
Révision_Projet = "0",
Statut_Projet = "Validé"
};
DateTime dateDebut = new DateTime(2018, 11, 30);
Plannings planning = new Plannings()
{
//ID_Planning = 1,
Date_Début = dateDebut,
ID_Projet = 1
};
context.SaveChanges();
}
Plannings.cs 模型
using System.ComponentModel.DataAnnotations;
namespace Projet.Models
{
public class Plannings
{
[Key]
public int ID_Planning { get; set; }
[Required]
public System.DateTime Date_Début { get; set; }
public Nullable<System.DateTime> Date_Fin { get; set; }
public System.DateTime Date_Est { get; set; }
public int ID_Projet { get; set; }
public Projets Projets { get; set; } = null!;
}
}
ProjetContext.cs
//using System.Data.Entity;
using Microsoft.EntityFrameworkCore;
using Projet.Models;
namespace Projet
{
public class ProjetContext : DbContext
{
public ProjetContext()
{
}
public ProjetContext(DbContextOptions options) : base(options)
{
}
public DbSet<Plannings> Plannings { get; set; }
public DbSet<Projets> Projets { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=;Database=;User Id=;Password=;TrustServerCertificate=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Projets>()
.HasOne(e => e.Plannings)
.WithOne(e => e.Projets)
.HasForeignKey<Projets>(e => e.ID_Projet).IsRequired();
}
}
}
///
Projets.cs
using System.ComponentModel.DataAnnotations;
namespace Projet.Models
{
public class Projets
{
[Key]
public int ID_Projet { get; set; }
[Required]
public string Nom_Projet { get; set; }
public string Description_Projet { get; set; }
[Required]
public string Version_Projet { get; set; }
[Required]
public string Révision_Projet { get; set; }
[Required]
public string Statut_Projet { get; set; }
public Plannings? Plannings { get; set; }
}
}
您似乎忘记将
projet
实体上的 Plannings 属性分配给 planning
实体,以便上下文可以正确跟踪两个相关对象。