Search code examples
.netentity-frameworkdomain-driven-designentity-framework-5ddd-repositories

Mapping Entities with Entity Framework 5 code first


I have 2 entities, a Patient that has a collection of studies.

public class Patient
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<Study> Studies { get; set; }
}

public class Study
{
    public Guid Id { get; set; }
    public Guid PatientId { get; set; }
    public string Name { get; set; }
}

I want to map this object to 2 tables in the database "Patients" and "Studies". What should be the syntax for doing this? I am using "EntityTypeConfiguration".

class PatientEntityTypeConfiguration : EntityTypeConfiguration<Patient>
{
    public PatientEntityTypeConfiguration()
    {
        this.HasKey(p => p.Id);

        this.Property(p => p.Name)
            .HasMaxLength(50)
            .IsRequired();

        //TODO: Map the studies!!!

        this.ToTable("Patients");
    }
}

Solution

  • First, you shouldn't have to manually create the plural versions of the tables unless you are specifically turning this off with your own implementation of the PluralizationService

    I would update your model a bit:

    public class Study
    {
        public Guid Id { get; set; }
        public virtual Guid PatientId { get; set; }
        //Add the navigation for Patient
        public virtual Patient Patient {get;set;}
        public string Name { get; set; }
    }
    

    Your mapping would look like this. By making the properties virtual you allow for Lazy Loading:

    class PatientEntityTypeConfiguration : EntityTypeConfiguration<Patient>
    {
        public PatientEntityTypeConfiguration()
        {
           HasKey(p => p.Id);
    
           Property(p => p.Name)
                .HasMaxLength(50)
                .IsRequired();
    
           HasMany(p => p.Studies)
           .WithRequired(s => s.Patient)
           .HasForeignKey(s => s.PatientId).WillCascadeOnDelete(false);
    
    
        }
    }