5

If I have a User class that has these properties:

    public Guid UserPreferenceId { get; set; }
    public virtual DefaultUserPreference UserPreference { get; set; }

    public Guid SecondaryUserPreferenceId { get; set; }
    public virtual DefaultUserPreference SecondaryUserPreference { get; set; }

How can I get this to make via fluent API? When I try to run this it says:

Introducing FOREIGN KEY constraint on table 'Users' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

I've seen a few of these questions but they always involve one single navigation property and one collection. Also the relationship is unidirectional, but it could be bidirectional if it had to be, not sure if that matters.

SventoryMang
  • 10,275
  • 15
  • 70
  • 113

1 Answers1

5

Entity Framework creates relationships with Cascade Delete on by default. Creating two relationships from one entity to another type tries to create two cascade-delete relationships, which the database will throw the error you saw for.

Use the Code-First Fluent Configuration to remove the Cascade Delete on one or both of the relationships:

modelBuilder.Entity<User>()
    .HasOptional(u => u.UserPreference)
    .WithMany()
    .WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
    .HasOptional(u => u.SecondaryUserPreference)
    .WithMany()
    .WillCascadeOnDelete(false);
Richard
  • 29,854
  • 11
  • 77
  • 120
  • Okay so I have to make it bidirectional then? – SventoryMang Jun 19 '13 at 21:23
  • Nope, updated the answer with one which works without bi-directional. You just need to alter the fluent config line to be appropriate to what you want. – Richard Jun 19 '13 at 21:28
  • That caused: Multiplicity conflicts with the referential constraint in Role 'DefaultUser_DefaultUserPreference_Target' in relationship 'DefaultUser_DefaultUserPreference'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. It did "work" (not throw an error) when I made it bidirectional but the SecondaryUserPreferenceId did not get set to a FK key. – SventoryMang Jun 19 '13 at 21:36
  • That's upto you then - If both UserPreference fields are required, then change `HasOptional` to `HasRequired`. If not, change your Guid foreign key types to be `Guid?` – Richard Jun 19 '13 at 21:38
  • Yeah I just figured that out, got it working both uni and bi directional and the FK problem was my issue (typo). Thanks! – SventoryMang Jun 19 '13 at 21:40