【问题标题】:Mapping Entities with Entity Framework 5 code first首先使用 Entity Framework 5 代码映射实体
【发布时间】:2013-01-03 07:53:33
【问题描述】:

我有 2 个实体,一个有一系列研究的患者。

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

我想将此对象映射到数据库“Patients”和“Studies”中的 2 个表。 这样做的语法应该是什么? 我正在使用“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");
    }
}

【问题讨论】:

标签: .net entity-framework domain-driven-design entity-framework-5 ddd-repositories


【解决方案1】:

首先,您不必手动创建表的复数版本,除非您使用自己的 PluralizationService 实现专门将其关闭

我会稍微更新一下你的模型:

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

您的映射将如下所示。通过使属性虚拟化,您可以进行延迟加载:

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


    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多