How can I use EF Code First to declare a one-to-many relationship?

前端 未结 2 1414
走了就别回头了
走了就别回头了 2021-02-06 09:08

I\'m trying to define a simple one-to-many relationship between two poco\'s, using the Entity Framework fluent API.

~ Team ~
public int TeamId {          


        
2条回答
  •  终归单人心
    2021-02-06 09:31

    I think this object model is what you are looking for:

    public class Team
    {    
        public int TeamId { get; set; }
        public ICollection TeamMembers { get; set; } 
        public Player CreatedBy { get; set; } 
    }
    
    public class Player
    {
        public int PlayerId { get; set; }
        public Team Team { get; set; } 
    }       
    
    public class Context : DbContext
    {
        public DbSet Players { get; set; }
        public DbSet Teams { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                        .HasOptional(p => p.Team)
                        .WithMany(t => t.TeamMembers)
                        .Map(c => c.MapKey("TeamId"));
    
            // Or alternatively you could start from the Team object:
            modelBuilder.Entity()
                        .HasMany(t => t.TeamMembers)
                        .WithOptional(p => p.Team)
                        .Map(c => c.MapKey("TeamId"));
        }
    }
    

    BTW, the following fluent API code that you are using is not correct:

    ...HasOptional(x => x.TeamMembers)
    

    Because TeamMembers is a collection and cannot be used by HasOptional method which always has to be invoked with a single object.

    Update - HasRequired vs. HasOptional:

    While they both set up an association, they deliver slightly different results and have different requirements:

    • If it's a FK association (the FK property is exposed on the dependent object) then it must be a nullable type when using HasOptional and non-nullable type when using HasRequired or Code First will throw.

    • Code First will automatically switch cascade deletes on when using HasRequired method.

    • The other difference is the EF runtime behavior when it comes to deletion. Consider a scenario where we want to delete the principal object (e.g. Team) while it has a dependent object (e.g. Player) and cascade delete is switched off. With HasOptional EF runtime will silently update the dependent FK column to null while with HasRequired EF will throw and ask you to either explicitly remove the dependent object or relate it to another principal object (If you want to try this you should be aware that in both cases both principal and dependent objects must be already loaded in context so that EF will have a track of them).

提交回复
热议问题