Search code examples
c#configurationentity-framework-coreforeign-keysrelation

Should I specify a relationship in EF Core twice in both configurations or only in one?


Should I specify a relationship in EF Core twice in both configurations or only in one?

E.g. I have these two models:

public class A 
{
   public int Id { get; set; }
   public int BId { get; set; }

   public B B { get; set; }
}

public class B 
{
   public int Id { get; set; }

   public ICollection<A> As { get; set; }
}

And I have the configuration:

    public void Configure(EntityTypeBuilder<A> builder)
    {
        builder
            .HasKey(a => new { a.Id, a.BId });

        builder
            .HasIndex(a => new { a.Id, a.BId })
            .IsUnique()
            .IsClustered();

        builder
            .HasOne(a => a.B)
            .WithMany(b => b.As)
            .HasForeignKey(a => a.BId)
            .IsRequired(true);
    }

Should I now add also the:

    public void Configure(EntityTypeBuilder<B> builder)
    {
        builder
            .HasKey(b => b.Id);

        builder
            .HasIndex(b => b.Id)
            .IsUnique()
            .IsClustered();

        builder
            .HasMany(b => b.As)
            .WithOne(a => a.B)
            .HasForeignKey(a => a.BId)
            .IsRequired(true);
    }

or was the first configuration enough (and hence the second will have no effect) ?

I really can not find an answer to this question on the internet, so I was hoping someone here would now.


Solution

  • No, You should not.

    One configuration is absolutely enough.

    See the docs in following link (Simple blog sample) :

    https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        
        // Navigation properties
        public List<Post> Posts { get; set; }
    
    }
        
    public class Post
    {
         public int PostId { get; set; }
         public string Title { get; set; }
         public string Content { get; set; }
    
         // Navigation properties
         public Blog Blog { get; set; }
     }
    
    public class MyContext : DbContext
    {
          public DbSet<Blog> Blogs { get; set; }
          public DbSet<Post> Posts { get; set; }
        
          protected override void OnModelCreating(ModelBuilder modelBuilder)
         {
              modelBuilder.Entity<Post>()
                          .HasOne(p => p.Blog)
                          .WithMany(b => b.Posts);
            }
        }
    

    If you are not interested in to configuring explicitly, EfCore has 4 Conventions (no configuration needed) for one to many relationships. Following link explains completely :

    https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx