SQLite User Forum

Foreign Key Constraint Failed In EF Core 6.0
Login

Foreign Key Constraint Failed In EF Core 6.0

(1.1) By Incredible Informatics (incridibleinformatics) on 2022-07-27 15:09:23 edited from 1.0 [link] [source]

Foreign Key Constraint Failed In EF Core 6.0 using Windows Forms

I am using EF Core with windows forms. I am having issues with auto generating Primary Key in a transaction where the Primary key is referenced in a foreign key. Lets see the following example:

Class


public class Class1
{
    [Key]
    public virtual string Id {get;set;}
    public virtual string Name {get;set;}
    public IEnumerable<Class2> Class2s {get;set;}
}

public class Class2
{
    public virtual string Id {get;set;}
    public virtual string Name {get;set;}
    public virtual string Class1Id {get;set;}
    public virtual Class1 Class1 {get;set;}
}

DbContext Model

modelBuilder.Entity<Class1>().HasKey(e => e.Id);
modelBuilder.Entity<Class1>().Property(e => e.Id).ValueGeneratedOnAdd();

modelBuilder.Entity<Class2>().HasKey(e => e.Id);
modelBuilder.Entity<Class2>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<Class2>().HasOne(e => e.Class1).WithMany(e => e.Class2s).HasForeignKey(e => e.Class1Id ).IsRequired(true).OnDelete(DeleteBehavior.Restrict);

Now this code does not work

var c1 = new Class1(){
    name = "Abc"
};
var c2s = new List<Class2>();
c2s.Add(
    new Class2(){
        Name = "Efg"
    }
);
c2s.Add(
    new Class2(){
        Name = "Deg"
    }
);
c2s.Add(
    new Class2(){
        Name = "Xyz"
    }
);

var tr = _context.Database.BeginTransaction();

try
{
    _context.Add(c);
    for(var i=0;i < c2s.Count;i++)
    {
        c2s[i].Class1Id = c1.Id;
    }
    _context.AddRange(c2s);
    _context.SaveChanges();
    tr.Commit();
}
catch (Exception ex)
{
    tr.Rollback();
}

But this works

var c1 = new Class1(){
    Id = Guid.NewGuid.ToString(),
    name = "Abc"
};
var c2s = new List<Class2>();
c2s.Add(
    new Class2(){
        Name = "Efg",
        Class1Id = c1.Id
    }
);
c2s.Add(
    new Class2(){
        Name = "Deg",
        Class1Id = c1.Id
    }
);

c2s.Add(
    new Class2(){
        Name = "Xyz",
        Class1Id = c1.Id
    }
);

var tr = _context.Database.BeginTransaction();

try
{
    _context.Add(c);
    _context.AddRange(c2s);
    _context.SaveChanges();
    tr.Commit();
}
catch (Exception ex)
{
    tr.Rollback();
}

(2) By Gunter Hick (gunter_hick) on 2022-07-28 06:03:25 in reply to 1.1 [source]

Judging from the numerous responses and "EF Core" being a Microsoft product, maybe you are in the wrong forum. If you can show what the actual calls (and arguments) the the SQLite C API are, then maybe someone here could help.

Also, "does not work" is a much too unspecific description of the discrepancy between your expectations and the results of your actions.