Entity Framework 4.1 InverseProperty Attribute and ForeignKey

前端 未结 2 1548
终归单人心
终归单人心 2020-11-29 04:02

I will create two references between Employee and Team entities with foreign keys. So I defined two entities as follow

public class Employee
{
    public int         


        
相关标签:
2条回答
  • 2020-11-29 04:34

    It is theoretically correct but SQL server (not Entity framework) doesn't like it because your model allows single employee to be a member of both First and Second team. If the Team is deleted this will cause multiple delete paths to the same Employee entity.

    This cannot be used together with cascade deletes which are used by default in EF code first if you define foreign key as mandatory (not nullable).

    If you want to avoid the exception you must use fluent mapping:

    public Context : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Team> Teams { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity<Employee>()
                        .HasRequired(e => e.SecondTeam)
                        .WithMany(t => t.SecondEmployees)
                        .HasForeignKey(e => e.FirstTeamId)
                        .WillCascadeOnDelete(false);
    
            ...
        }
    }
    

    This will result in scenario where you must delete members of SecondTeam manually before you delete the team.

    0 讨论(0)
  • 2020-11-29 04:40

    All is correct in previous answer, but one thing is wrong

        modelBuilder.Entity<Employee>()
                    .HasRequired(e => e.SecondTeam)
                    .WithMany(t => t.SecondEmployees)
                    .HasForeignKey(e => e.SecondTeamId) // mistake
                    .WillCascadeOnDelete(false);
    

    FirstTeamId instead of SecondTeamId will cause that in SecondTeam navigation property will be always FirstTeam

    0 讨论(0)
提交回复
热议问题