0

I have three tables:

CREATE TABLE [dbo].[Committees] (
    [committee_id]          INT             IDENTITY (1, 1) NOT NULL,
    [Committee_name]        NVARCHAR (128)  NULL,
    [Committee_email]       NVARCHAR (128)  NULL,
    [Committee_inactive]    INT             NULL,
    [Committee_type]        NVARCHAR (50)   NULL,
    [Committee_description] NVARCHAR (1024) NULL,
    [Committee_chair_id]    INT             NOT NULL,
    [Committee_sponsor_id]  INT             NOT NULL,
    [Committee_end_date]    DATETIME2 (7)   NULL,
    [bMembershipOpen]       BIT             CONSTRAINT [DF_Committees_bMembershipOpen] DEFAULT ((0)) NOT NULL,
    CONSTRAINT [PK_Committees] PRIMARY KEY CLUSTERED ([committee_id] ASC),
    CONSTRAINT [FK_CommitteesChair_ToPersons] FOREIGN KEY ([Committee_chair_id]) REFERENCES [dbo].[Persons] ([Id]),
    CONSTRAINT [FK_CommitteesSponsor_ToPersons] FOREIGN KEY ([Committee_sponsor_id]) REFERENCES [dbo].[Persons] ([Id])
);

CREATE TABLE [dbo].[Persons] (
    [Id]    INT            IDENTITY (1, 1) NOT NULL,
    [Name]  NVARCHAR (128) NULL,
    [Email] NVARCHAR (128) NULL,
    CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED ([Id] ASC)
);

and

CREATE TABLE [dbo].[CommitteeMembers] (
    [CommitteeId] INT NOT NULL,
    [PersonId]    INT NOT NULL,
    PRIMARY KEY CLUSTERED ([CommitteeId] ASC, [PersonId] ASC),
    CONSTRAINT [FK_CommitteeMembers_ToCommittee] FOREIGN KEY ([CommitteeId]) REFERENCES [dbo].[Committees] ([committee_id]),
    CONSTRAINT [FK_CommitteeMembers_ToPerson] FOREIGN KEY ([PersonId]) REFERENCES [dbo].[Persons] ([Id])
);

I have two classes associated with Committees and Persons

 public class Committee {

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("committee_id")]
        [Key]
        public int Id { get; set; }

        [Column("Committee_chair_id")]
        [ForeignKey("Chairman")]
        [Required(ErrorMessage = "Committee must have a Chairman")]
        public int ChairmanId { get; set; }

        [Column("Committee_sponsor_id")]
        [ForeignKey("Sponsor")]
        [Required(ErrorMessage = "Committee must have a Sponsor")]
        public int SponsorId { get; set; }

        [Column("Committee_name")]
        [MinLength(3, ErrorMessage = "Committee Name must be at least 3 characters long")]
        [MaxLength(128, ErrorMessage = "Committee Name cannot be longer than 128 characters")]
        [Required(ErrorMessage = "Committee must have a name")]
        public string Name { get; set; }

        [Column("Committee_email")]
        [EmailAddress]
        [Required(ErrorMessage = "Committee must have an Email Address")]
        public string Email { get; set; }

        [Column("Committee_inactive")]
        public int? Inactive { get; set; }

        [Column("Committee_type")]
        [Required(ErrorMessage = "Committee must have a Type")]
        public string Type { get; set; }

        [Column("Committee_description")]
        [MaxLength(1000, ErrorMessage = "Committee Name cannot be longer than 1000 characters")]
        public string Description { get; set; }

        [Column("Committee_end_date")]
        public DateTime? EndDate { get; set; }

        [Column("bMembershipOpen")]
        [DefaultValue(false)]
        [Display(Name="Membership Open")]
        [Required]
        public bool MembershipOpen { get; set; }

        public Person Chairman { get; set; }

        public Person Sponsor { get; set; }

        public virtual ICollection<Person> Members { get; set; }

        public virtual ICollection<Note> Notes { get; set; }  

        public virtual ICollection<NextStep> NextSteps { get; set; } 

        public virtual ICollection<Outcome> Outcomes { get; set; } 

        public virtual ICollection<Video> Videos { get; set; } 
    }

and

public class Person {

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required(ErrorMessage = "You must specify a name")]
    [MaxLength(128, ErrorMessage = "Name cannot be longer than 128 characters")]
    public string Name { get; set; }

    [EmailAddress]
    [MaxLength(128, ErrorMessage = "Email Address cannot be longer than 128 characters")]
    public string Email { get; set; }

    public virtual ICollection<Committee> Committees { get; set; } 
}

and I have the following in my DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Committee>()
        .HasMany(c => c.Members)
        .WithMany(m => m.Committees)
        .Map(m=> {
            m.ToTable("CommitteeMembers");
            m.MapLeftKey("PersonId");
            m.MapRightKey("CommitteeId");
        });

    modelBuilder.Entity<Committee>()
        .HasMany(c => c.Notes)
        .WithRequired(n => n.Committee);

    modelBuilder.Entity<Committee>()
        .HasMany(c => c.NextSteps)
        .WithRequired(n => n.Committee);

    modelBuilder.Entity<Committee>()
        .HasMany(c => c.Outcomes)
        .WithRequired(o => o.Committee);

    modelBuilder.Entity<Committee>()
        .HasMany(c => c.Videos)
        .WithRequired(v => v.Committee);

    modelBuilder.Entity<Committee>()
        .HasRequired(c => c.Chairman);

    modelBuilder.Entity<Committee>()
        .HasRequired(c => c.Sponsor);

    modelBuilder.Entity<Person>()
        .Map(t => t.ToTable("Persons"));
}

All of my navigation properties work on my models except Committee.Members and Person.Committees. Whenever I try to save the DbContext after adding a Person to a Committee or a Committee to a Person I get an error like the following:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CommitteeMembers_ToCommittee". The conflict occurred in database "EquipNetCommitteeDb", table "dbo.Committees", column 'committee_id'. The statement has been terminated.

Does anyone have any idea what I am doing wrong? This should work. I have done it many times before and I think I just need another set of eyes on it.

1 Answer 1

1

So it looks like Entity Framework did not like that I had already created Foreign Keys in the CommitteeMembers table. Once I removed those and let Entity Framework manage the relationships it worked. I'm not sure if this is how it is supposed to work though. If anyone knows anything about why I could not specify foreign keys in the table definition I would be curious to know the answer.

2
  • 2
    I think some of entity creators choosed to "simplify" the concept of foreign keys and relationship between two entitys. They want Entity to automatically design the relations between object. I can't explain it very well as i don't know much of what happens from inside the framework but here : ladislavmrnka.com/2011/05/… Sep 14, 2015 at 20:02
  • 1
    What a great response. That post contained a very lucid explanation of why what I was doing, while technically correct, did not fit with the way the Entity Framework expects me to work. Thanks a lot. Sep 15, 2015 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.