您好,我有一个数据库,其中有3个表设计成三角形,如下所示:
File has many Page
Page has many Segment
File has many Segment
当我尝试插入类型的实体时,File出现以下错误:
InnerException {“ MERGE语句与FOREIGN KEY约束\” FK_Segment_File_FileId \“冲突。冲突发生在数据库\” mydatabase \“,表\” dbo.File \“的列'Id'中。\ r \ n已终止。“} System.Exception {Microsoft.Data.SqlClient.SqlException} 楷模
public class File
{
public int Id{get;set;}
public ICollection<Segment> Segments{get;set;}
public ICollection<Pages> Pages{get;set;}
}
public class Page
{
public int Id{get;set;}
public ICollection<Segment> Segments{get;set;}
}
public class Segment
{
public int Id{get;set;}
public Page Page{get;set;}
public int PageId{get;set;} //foreign key from page
public File File{get;set;}
public int FileId{get;set;} //foreign key from file
}
语境
public class MyContext: DbContext {
public DbSet<Segment> Segments { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<File> Files { get; set; }
public SXSContext(DbContextOptions<MyContext> options):base(options) {
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<File>(ent => {
ent.ToTable("File");
ent.HasKey(x => x.Id);
ent.Property(x => x.Id).IsRequired();
});
modelBuilder.Entity<Page>(ent => {
ent.ToTable("Page");
ent.HasKey(x => x.Id);
ent.Property(x => x.Id).IsRequired();
ent.Property(x => x.FileId).IsRequired();
ent.HasOne(y => y.File).WithMany(t => t.Pages).HasForeignKey(g => g.FileId).OnDelete(DeleteBehavior.NoAction);
});
modelBuilder.Entity<Segment>(ent => {
ent.ToTable("Segment");
ent.HasKey(x => x.Id);
ent.Property(x => x.Id).IsRequired();
ent.Property(x => x.PageId).IsRequired();
ent.Property(x => x.FileId).IsRequired();
ent.HasOne(y => y.Page).WithMany(t => t.Segments).HasForeignKey(g => g.PageId).OnDelete(DeleteBehavior.Cascade);
ent.HasOne(y => y.File).WithMany(t => t.Segments).HasForeignKey(g => g.FileId).OnDelete(DeleteBehavior.Cascade);
});
}
}
用法
static async Task Main(string[] args) {
await Task.Delay(1);
DbContextOptionsBuilder<MyContext> optionsBuilder = new DbContextOptionsBuilder<MyContext>();
optionsBuilder.UseSqlServer(connectionString);
SXSContext context = new SXSContext(optionsBuilder.Options);
context.Database.EnsureCreated();
List<Page> pages = new List<Page>{
new Page{
Segments = new List<Segment> {
new Segment{ },
new Segment{ },
new Segment{ }}
},
new Page{
Segments = new List<Segment> {
new Segment{ },
new Segment{ }}
}
};
File file = new File { Pages = pages };
context.Files.Add(file);
context.SaveChanges();
int val = await context.SaveChangesAsync();
}
PS难道是一个问题,我有Segment外交键作为required,他们可能他们的父母之前得到插入File和Page?
应该如何像这样的模式被插入?我开始与File我有Pages和Segments他们不posess id的,直到插入。
可以将它们插入一个操作中,还是必须从根开始插入(对于我而言是)File?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。