When I add a new a class to my domain and add it to my DBContext for example:
I add this class
namespace Zoo.Domain
{
[Table("Owner")]
public partial class Owner
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public string Email { get; set; }
public virtual ICollection<Animal> Animals { get; set; }
}
}
And add this to my Animal class:
public virtual ICollection<Owner> Owners { get; set; }
And add this to my DBContext:
public virtual DbSet<Owner> Owners { get; set; }
And next I add a new migration by executing the 'add-migration AddAnimalOwners' command and the 'update-database' command in the Package Manager Console.
EntityFrameWork seems to create the relationship between Animal and Owner for me, but if that's the case why does ModelBuilder exists and when would I need it when I am updating my database? For example when I first created my database the following code appeared in my DBContext class:
modelBuilder.Entity<Animal>()
.Property(e => e.Name)
.IsUnicode(false);
modelBuilder.Entity<Animal>()
.Property(e => e.Type)
.IsUnicode(false);
modelBuilder.Entity<Animal>()
.Property(e => e.ImgUrl)
.IsUnicode(false);
modelBuilder.Entity<Animal>()
.HasMany(e => e.Bookings)
.WithMany(e => e.Animals)
.Map(m => m.ToTable("Animal_has_booking").MapLeftKey("AnimalID").MapRightKey("BookingID"));
It also appears to not generate a Modelbuilder for every Model in my domain when i first created my database
modelBuilder is used to allow you to configure aspects of the model that are specific to a given database. It is called by the framework when your context is first created to build the model and its mappings in memory. For example here:
modelBuilder.Entity<Animal>()
.HasMany(e => e.Bookings)
.WithMany(e => e.Animals)
It is specifying that there is a Many-to_many relationship between Bookings and Animals. If you don't have anything to specify, you would not need to use the modelBuilder, that is why you don't see it for every Model.