简体   繁体   English

使用多对多关系保存时的外键冲突EF6

[英]Foreign Key Violation when saving with a Many To Many relationship EF6

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 我的DbContext中有以下内容

protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); 受保护的重写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. 我的所有导航属性都可以在我的模型上使用,除了Committee.Members和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: 每当在将人员添加到委员会或将委员会添加到人员后尝试保存DbContext时,都会出现如下错误:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CommitteeMembers_ToCommittee". INSERT语句与FOREIGN KEY约束“ FK_CommitteeMembers_ToCommittee”冲突。 The conflict occurred in database "EquipNetCommitteeDb", table "dbo.Committees", column 'committee_id'. 数据库“ EquipNetCommitteeDb”的表“ dbo.Committees”的列“ 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. 我之前已经做过很多次了,我想我只需要再看一点。

So it looks like Entity Framework did not like that I had already created Foreign Keys in the CommitteeMembers table. 因此,似乎实体框架不喜欢我已经在CommitteeMembers表中创建了外键。 Once I removed those and let Entity Framework manage the relationships it worked. 删除这些内容并让Entity Framework管理它们之间的关系后。 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. 如果有人知道为什么我不能在表定义中指定外键,我很想知道答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM