0

The error occurs when saving the object couple.

Code

Data class

public class User
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public bool IsApproved { get; set; }
    public bool IsBlock { get; set; }
    public bool IsGuest { get; set; }
    public string CodeGuest { get; set; }
    public Gender Gender { get; set; }
    public DateTime? Birth { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
    public virtual Couple Couple { get; set; }

    public User()
    {
        Id = Guid.NewGuid();
    }
}


public class Couple
{
    public Guid Id { get; private set; }
    public string UrlKeyword { get; set; }
    public virtual User Groom { get; set; }
    public virtual User Bride { get; set; }
    public DateTime? Marriage { get; set; }
    public DateTime? Dating { get; set; }
    public DateTime? Engagement { get; set; }

    public virtual ICollection<User> Users { get; set; }

    public Couple()
    {
        Id = Guid.NewGuid();
    }
}

Context and configurations

public class DataContext : DbContext
{
    #region Collections

    public DbSet<Role> Roles { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Couple> Couples { get; set; }

    #endregion

    public DataContext()
    {
        Database.SetInitializer(new AndMarriedInitializer());

        if (!Database.CreateIfNotExists())
            Database.CreateIfNotExists();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}

public class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        HasKey(p => p.Id).
            Property(p => p.Id)
                .IsRequired();

        Property(p => p.FirstName)
            .HasMaxLength(60)
            .IsRequired();

        Property(p => p.LastName)
            .HasMaxLength(120)
            .IsRequired();

        Property(p => p.Email)
            .HasMaxLength(120)
            .IsRequired();

        Property(p => p.Password)
            .HasMaxLength(60);

        Property(p => p.CodeGuest)
            .HasMaxLength(60);

        HasRequired(u => u.Couple).WithRequiredPrincipal();
    }
}

public class CoupleConfiguration : EntityTypeConfiguration<Couple>
{
    public CoupleConfiguration()
    {
        HasKey(p => p.Id)
            .Property(p => p.Id)
            .IsRequired();

        Property(p => p.UrlKeyword)
            .IsRequired()
            .HasMaxLength(25);

        HasRequired(p => p.Groom).WithRequiredPrincipal().WillCascadeOnDelete();
        HasRequired(p => p.Bride).WithRequiredPrincipal().WillCascadeOnDelete();
    }
}

public class AndMarriedInitializer : DropCreateDatabaseIfModelChanges<DataContext>
{
    protected override void Seed(DataContext context)
    {
        context.Roles.Add(new Role
                              {
                                  Name = Constants.RoleAdmin
                              });
        context.Roles.Add(new Role
                              {
                                  Name = Constants.RoleCouple
                              });
        context.Roles.Add(new Role
                              {
                                  Name = Constants.RoleGuest
                              });

        context.SaveChanges();

        base.Seed(context);
    }
}

Question

Do not know if configured correctly, but we relate to the Couple with User is: 1 to 1.

Do not quite understand how the WithRequiredPrincipal and WithRequiredDependent

Error

On SaveChanges() =>

The INSERT statement conflicted with the FOREIGN KEY constraint "User_Couple". The conflict occurred in database "andmarried", table "dbo.Users", column 'Id'. The statement has been terminated.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
ridermansb
  • 10,779
  • 24
  • 115
  • 226

1 Answers1

0

With this line of code:

public UserConfiguration()
{
//...
    HasRequired(u => u.Couple).WithRequiredPrincipal();
//...

You're requiring all users to be "coupled" all the time.

So, when you commit your changes, are all the users you created married? If not, remove that foreign key constraint. (Just leave the couple ones in and you should be O.K.)

  • Yes, but what I want is that every user is associated with a couple. What defines whether it is a couple or a guest are the roles; – ridermansb Oct 17 '11 at 16:12
  • In any case, it sounds like you're committing a database state where a User exists with no couple. Perhaps auto-commit is a problem? Can you show the code actually making the calls into these objects? ie: What is being created and saved and then the actual line that fails with an exception? Note: User <-> Couple sounds like either 2 <-> 1 or maybe many <-> 1 based on your last comment. –  Oct 17 '11 at 17:05
  • `public Couple Add(Couple entity) { // Add Roles var role = (from r in RoleRepository.GetAll() where r.Name == Constants.RoleCouple select r).SingleOrDefault(); entity.Bride.Roles.Add(role); entity.Groom.Roles.Add(role); //entity.Users.Add(entity.Bride); //Problem here //entity.Users.Add(entity.Groom); //Problem here return Repository.Add(entity); }` See the `//Problem here` line Do not know if I leave this line commented out, or remove comment. The relationship is 2 couples for 1 user – ridermansb Oct 17 '11 at 17:46
  • If I remove the comment the following error occurs: `Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.` – ridermansb Oct 17 '11 at 17:50
  • Have you tried WithMany() for the user <-> couple relationship? –  Oct 17 '11 at 18:05
  • `HasRequired(u => u.Couple).WithMany();` in `UserConfiguration` class **Error on SaveChanges()** `Entities in 'DataContext.Users' participate in the 'User_Couple' relationship. 0 related 'User_Couple_Target' were found. 1 'User_Couple_Target' is expected.` – ridermansb Oct 17 '11 at 18:08
  • Reading this: http://www.codeproject.com/Articles/165720/Using-the-Code-First-Model-Configuration-Classes?display=Print Looks like a list of Users in the other object is the expected way to do the one to many. Also, for the two-way relationship it looks like you have to use the form of With*** that takes in the function. Sorry I'm not more helpful. –  Oct 17 '11 at 18:24
  • I do not understand what I'm doing wrong. The relationship is relatively simple: a couple will always have two users, yet thanks for the tip, I'll read the article! – ridermansb Oct 18 '11 at 09:57
  • **Table** `Couples: ID GroomID -> UserID BrideID -> UserID` **Table** `User: ID CoupleID` ---------- Couple `Class Guid ID User Groom User Bride` User `class Guid ID Couple Couple` ------------- **for each couple there are two users, ever!** – ridermansb Oct 18 '11 at 10:43