문제

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");
    }
}
도움이 되었습니까?

해결책

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);


    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top