Base solution for your next web application
Open Closed

Migration Delete action issue #12507


User avatar
0
stanley5389 created

Hi, Migration time onDelete: ReferentialAction.Restrict I use here Restrict But Db Show NO_ACTION?

But If I use Cascade Working fine!

Markdown is supported
Copy & paste or drag & drop images (max 30 MB per image)

19 Answer(s)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    If your goal is to strictly prevent deletes when related child records exist (like Restrict implies), you don’t need to change anything SQL Server will enforce this with the NO ACTION constraint (even if the label is different). The behavior is the same: the delete operation will be blocked if related Developer rows exist for a given Address. So although the migration says Restrict and the database shows NO ACTION, functionally they are equivalent in SQL Server.

    If you want automatic deletion of related records, use Cascade but be aware that it will also delete all dependent data.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Hi, I try to delete Address it is deleted. App Crash

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Please get back me ASAP. It's urgent

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    I will try to reproduce this issue by going over your project again and will identify the necessary steps to provide a solution as soon as possible.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    If you want to delete an Address entity that is currently linked to one or more Developer entities via a foreign key (AddressId), and the foreign key is configured with Restrict delete behavior, you must first remove the reference from the Developer(s) before deleting the Address.

    If you want to continue using the Restrict behavior, this step will always be required to avoid foreign key constraint violations.

    In other words, before calling the delete method on the _addressRepository, you should find all developers associated with that address and set their AddressId to null.

    Example

    var developers = await _developerRepository.GetAllListAsync(d => d.AddressId == addressId);
    
    foreach (var developer in developers)
    {
        developer.AddressId = null;
        await _developerRepository.UpdateAsync(developer);
    }
    
    // Now it's safe to delete the address
    await _addressRepository.DeleteAsync(addressId);
    

    This ensures that the Address entity is no longer referenced by any Developer entities, avoiding a foreign key constraint violation when the deletion is attempted.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Bro, I intended it for a specific purpose. The address table has no entity relationship. The developer table has a relationship with the address table. The other thing Now Developer, later I add 100 how? I need to add 100 table here? That's why entity comes here. I use entity

    Example: Address A Developer A Developer A linked the Address A. If I go to the Address page and try to delete Address A, By action it should not delete & it should throw an error. But here delete works? How? Entity I have restricted! You got my point?

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    Ensure Foreign Key Is Actually Created in the Database

    Just writing .OnDelete(DeleteBehavior.Restrict) in your code is not enough. You need to make sure the relationship is applied to the database correctly.

    This step will solve your problem. In your CoreSynDbContext, make sure you have: OnModelCreating()

    modelBuilder.Entity<Developer>()
        .HasOne(d => d.Address)
        .WithMany() // or .WithMany(a => a.Developers)
        .HasForeignKey(d => d.AddressId)
        .OnDelete(DeleteBehavior.Restrict);
    

    If you're missing WithMany() or the configuration is partial, the FK might not be created at all.

    Check the Migration File:

    After generating the migration, you should see something like:

    onDelete: ReferentialAction.Restrict
    


    Check in SQL Server if the Foreign Key exists:

    Run this query:

    SELECT * FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID('Developer');
    

    Or open the Developer table in SSMS and check the Foreign Keys section.


    Make Sure SQL Server Is Using ON DELETE NO ACTION

    In SQL Server, Restrict becomes NO ACTION. You can verify the constraint by scripting out the table or checking the relationship:

    FOREIGN KEY (AddressId) REFERENCES Address(Id) ON DELETE NO ACTION
    

    Add Safety Check in AppService

    Even if your FK is set correctly, it's good practice to prevent deletes through application logic too:

    public async Task DeleteAddress(EntityDto input)
    {
        var isUsed = await _developerRepository.GetAll()
            .AnyAsync(d => d.AddressId == input.Id);
    
        if (isUsed)
        {
            throw new UserFriendlyException("This address is used by a developer and cannot be deleted.");
        }
    
        await _addressRepository.DeleteAsync(input.Id);
    }
    

    This guarantees that your application prevents deletion even if the database does not.


    What If You Have 100 Related Tables in the Future?

    You don’t need to configure each one manually. You can use a global convention in your OnModelCreating method:

    foreach (var foreignKey in modelBuilder.Model
        .GetEntityTypes()
        .SelectMany(e => e.GetForeignKeys()))
    {
        foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
    }
    

    This will apply Restrict to all foreign keys in your model automatically.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Without adding above latest project working. How? I'll share the project with you If you want. How to fix this in my Real project. What code need to change?

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    I Figured it out the Issue. If I generate only .Net & angular Fine Working. But I choose Maui, Unit Test All Migration delete not works. Below I'll share the json try it out. Give me the solution. How to fix this?

    Delete Not Working { "IsRegenerate": true, "MenuPosition": "Property", "RelativeNamespace": "Property", "EntityName": "Address", "EntityNamePlural": "Addresses", "TableName": "Addresses", "PrimaryKeyType": "Guid", "BaseClass": "FullAuditedEntity", "EntityHistory": true, "AutoMigration": true, "UpdateDatabase": true, "CreateUserInterface": true, "CreateViewOnly": true, "CreateExcelExport": true, "CreateExcelImport": true, "IsNonModalCRUDPage": false, "IsMasterDetailPage": false, "GenerateOverridableEntity": false, "GenerateUnitTest": true, "GenerateUiTest": true, "GenerateMobile": true, "CreateMauiView": true, "PagePermission": { "Host": true, "Tenant": true }, "Properties": [ { "Name": "AddressLine1", "Type": "string", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": true, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} }, { "Name": "Proof", "Type": "file", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": false, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} } ], "NavigationProperties": [], "NavigationPropertyOneToManyTables": [], "EnumDefinitions": [], "DbContext": null }

    Delete Works { "IsRegenerate": false, "MenuPosition": "Property", "RelativeNamespace": "Property", "EntityName": "Address", "EntityNamePlural": "Addresses", "TableName": "Addresses", "PrimaryKeyType": "Guid", "BaseClass": "Entity", "EntityHistory": false, "AutoMigration": true, "UpdateDatabase": true, "CreateUserInterface": true, "CreateViewOnly": true, "CreateExcelExport": true, "CreateExcelImport": true, "IsNonModalCRUDPage": false, "IsMasterDetailPage": false, "GenerateOverridableEntity": false, "GenerateUnitTest": false, "GenerateUiTest": false, "GenerateMobile": false, "CreateMauiView": false, "PagePermission": { "Host": true, "Tenant": true }, "Properties": [ { "Name": "AddressLine1", "Type": "string", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": true, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} } ], "NavigationProperties": [], "NavigationPropertyOneToManyTables": [], "EnumDefinitions": [], "DbContext": null }

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Hello?

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    We are trying to reproduce the issue based on your project. I will keep you informed here as we work on a solution. Thank you

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Okay. I'll be waiting for your response

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    [stanley5389] said: I Figured it out the Issue. If I generate only .Net & angular Fine Working.
    But I choose Maui, Unit Test All Migration delete not works.
    Below I'll share the json try it out. Give me the solution. How to fix this?

    Delete Not Working { "IsRegenerate": true, "MenuPosition": "Property", "RelativeNamespace": "Property", "EntityName": "Address", "EntityNamePlural": "Addresses", "TableName": "Addresses", "PrimaryKeyType": "Guid", "BaseClass": "FullAuditedEntity", "EntityHistory": true, "AutoMigration": true, "UpdateDatabase": true, "CreateUserInterface": true, "CreateViewOnly": true, "CreateExcelExport": true, "CreateExcelImport": true, "IsNonModalCRUDPage": false, "IsMasterDetailPage": false, "GenerateOverridableEntity": false, "GenerateUnitTest": true, "GenerateUiTest": true, "GenerateMobile": true, "CreateMauiView": true, "PagePermission": { "Host": true, "Tenant": true }, "Properties": [ { "Name": "AddressLine1", "Type": "string", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": true, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} }, { "Name": "Proof", "Type": "file", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": false, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} } ], "NavigationProperties": [], "NavigationPropertyOneToManyTables": [], "EnumDefinitions": [], "DbContext": null }

    Delete Works { "IsRegenerate": false, "MenuPosition": "Property", "RelativeNamespace": "Property", "EntityName": "Address", "EntityNamePlural": "Addresses", "TableName": "Addresses", "PrimaryKeyType": "Guid", "BaseClass": "Entity", "EntityHistory": false, "AutoMigration": true, "UpdateDatabase": true, "CreateUserInterface": true, "CreateViewOnly": true, "CreateExcelExport": true, "CreateExcelImport": true, "IsNonModalCRUDPage": false, "IsMasterDetailPage": false, "GenerateOverridableEntity": false, "GenerateUnitTest": false, "GenerateUiTest": false, "GenerateMobile": false, "CreateMauiView": false, "PagePermission": { "Host": true, "Tenant": true }, "Properties": [ { "Name": "AddressLine1", "Type": "string", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": true, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} } ], "NavigationProperties": [], "NavigationPropertyOneToManyTables": [], "EnumDefinitions": [], "DbContext": null }

    Reproduce issue like this. Got Any update?

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    Based on the JSON files you provided, we couldn’t reproduce your issue. We’ve tried different approaches, but to better understand what exactly you are trying to achieve, could you please send us the final state of your project along with step by step instructions to reproduce the issue? It would be very helpful if you could share this information with us via [email protected] email. Also, could you clarify what type of 'onDelete' you would like to use in this case?

    Thank you

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    See below example you can use your OWN JSON also. Relationship like below

    Let me know If you don't understand I'll send the projects.

    Scenario 1: Example Two tables Address & Developer. Address table No FK reference only PK Developer table has FK Address table. Step 1: I added address A Step 2: I added Developer A linked with address A Step 3: If I try to delete Address A it should not delete and throw Error correct? Like below Image If I generate code using PowerTool only .Net & angular Fine Working.

    Here I have Selected Only Tracking Entity only.

    PROBLEM HERE Scenario 2: Example Two tables Address & Developer. Address table No FK reference only PK Developer table has FK Address table. Step 1: I added address A Step 2: I added Developer A linked with address A Step 3: If I try to delete Address A it should not delete and throw Error correct? But here Address will delete. If I generate code using PowerTool only .Net & angular & Unit Test & Mobile Maui code.

    Here I have Selected Everything .Net & angular & Unit Test & Mobile Maui code.

    What I achieve here Why would I write extra code like below for safety check. Scenario 1 Works with out below code. Why Scenario 2 Not working? That's why we use Entity right OnDelete Restrict public async Task DeleteAddress(EntityDto input) { var isUsed = await _developerRepository.GetAll() .AnyAsync(d => d.AddressId == input.Id);

    if (isUsed)
    {
        throw new UserFriendlyException("This address is used by a developer and cannot be deleted.");
    }
    
    await _addressRepository.DeleteAsync(input.Id);
    

    }

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Got it? Any update?

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    In the scenario you described, the issue does not occur; however, when the generated entity has the base class Entity, a warning is displayed when trying to delete related data. On the other hand, when the entity is based on FullAuditedEntity, the deletion proceeds with "No Action" behavior, without any warning.

    We created an issue for this, you can follow the developments here.

    You can temporarily follow the steps outlined in this comment. This will resolve the issue in your desired scenario.

    Thank you for your feedback and detailed explanation.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Okay for now I'm using like this. Once done. Please ping me I'll update my project. Thanks & I'm waiting.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Thank you. I'll contact you once it's complete.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)