0

Here is my UserLog model:

public class UserLog
{
    public int Id { get; set; }
    public ApplicationUser Customer { get; set; }
    public DateTime LogDate { get; set; }
}

I created it for risk management purposes. The issue is whenever I want to delete a user from my AspNetUsers table I have to first delete the rows associated with the user from UserLog. However, doing this undermines the whole idea of risk management system in place.

Is there a way to remove the FKConstraint placed on the UserLog table? I know that if I remove ApplicationUser and rename Customer to Customer_Id code first will delete the row and the constraint, then, recreate it giving it the new name(even though the row is currently named Customer_Id). Is there a work around for this?

Skullomania
  • 2,225
  • 2
  • 29
  • 65
  • have you tried making your foreign key nullable: https://stackoverflow.com/a/5668835/2048391 Note I haven't tested how this will affect the deletion of the row (so please try this only in test environment not prod) – jyrkim Aug 30 '17 at 06:30

2 Answers2

2

alter table UserLog drop constraint FKconstraintName;

gsdev
  • 259
  • 4
  • 14
  • The only issue with doing that through sql is that when I use `update-database` from test to production that command will not be included – Skullomania Aug 29 '17 at 21:11
0

As explained here, removing the entity that shouldn't have the foreign key constraint and updating from the database is the easiest way to do it.

The hard way to do it, to answer your question, is to dig into the EDMX's XML and do it yourself.

The steps to do so, as outlined in the link:

  1. In the conceptual model, remove the FK property, typically something like ChildId or whatever.
  2. Still in the conceptual model, change the navigation property to be singular.
  3. Once again in the conceptual model, remove the ReferentialConstraint for your Association. Say you Association Name is something like FK_Child_Parent, just dump the ReferentialConstraint in there. Note you can also set the multiplicity here if you need to; you would set the correct multiplicity on the end point. Your options are *, 1, or 0..1.
  4. Now move down to the C-S Mapping Content (the mappings), and remove the ScalarProperty that corresponds to the foreign key you are removing.
  5. Finally, since you removed the ReferentialConstraint, you need to add an AssociationSetMapping instead. You can just append this to the end of the EntityContainerMapping section of the XML. Below, you can find a snippet of the AssociationSetMapping. Be sure to replace the attributes within the AssociationSetMapping that are all in caps.
C. Helling
  • 1,394
  • 6
  • 20
  • 34