Referential integrity ignored

I have a parent child relationship with a reference constraint so that a delete of the parent fails if the record has children.

A simple delete statement of a parent record with children fails as expected in SSMS, yet I am able to delete the record in my Radzen app: it acts as if I had configured a cascade delete.

Hi @semafox,

The code generated by Radzen will use cascade delete by default. For example:

[HttpDelete("{OrderID}")]
public IActionResult DeleteOrder(int key)
{
    var item = this.context.Orders
        .Where(i => i.OrderID == key)
        .Include(i => i.OrderDetails)
        .SingleOrDefault();

    if (item == null)
    {
        return NotFound();
    }

    this.OnOrderDeleted(item);
    this.context.Orders.Remove(item);
    this.context.SaveChanges();

    return new NoContentResult();
}

Best Regards,
Vladimir

Is the cascade occurring because of the .Include in the LINQ statement?

What would be the best way to modify this behavior (have a restrict delete for ex) so that the change does not get overwritten by the code generator?

Hi @semafox,

Indeed the Include will cause cascade. Currently there is no option to stop it however we can add it in the next release.

Best Regards,
Vladimir

The .Include is no longer necessary!? from EF core 2.1 they have lazy loading as an option.

This feature was introduced in EF Core 2.1.

The simplest way to use lazy-loading is by installing the Microsoft.EntityFrameworkCore.Proxies package and enabling it with a call to UseLazyLoadingProxies. For example:

C#

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);
Or when using AddDbContext:

C#

.AddDbContext<BloggingContext>(
    b => b.UseLazyLoadingProxies()
          .UseSqlServer(myConnectionString));

Perhaps this solves the problem?
Or is it corrected in the actual version of Radzen?

Kind Regards
Thomas

Hi Thomas,

I believe that lazy loading proxies are not related to cascading deletes. When you add Include to your query you are just telling your database to perform cascade delete:
https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete

The delete behavior configured in the EF Core model is only applied when the principal entity is deleted using EF Core and the dependent entities are loaded in memory

Best Regards,
Vladimir