如何在需要[一到两个]关系时映射实体?

时间:2015-03-31 04:36:30

标签: c# entity-framework

class Address { 
  // Properties 
}
class Account
{
  //Other Properties
  Public Address Permanent { get; set; }
  Public Address Current { get; set; }
}
class Other
{
  //Other Properties
  Public Address OtherAddress { get; set; }
}

一个帐户有两个地址永久和当前。我不能将Address类用作复杂类型,因为我需要一个数据库表来实现更简单的设计。我有其他需要地址实体的实体(一对一)。

处理这种情况的标准方法是什么?如何映射这些实体?

如果解决方案使用Entity Framework Code First Convention来实现这种关系,那将是很好的。

3 个答案:

答案 0 :(得分:2)

我不是EF的专家,但我认为你可以这样做,

 public class Account
 {
    [Key]
    public int Id {get;set;}

    ...

    public virtual PermanetAddress PermenentAddress {get;set;}
    public virtual CurrentAddress CurrentAddress {get;set;}
  }

  class Address
  {
     //properties
  }

  class PermanetAddress : Address
  {
     [ForeignKey("Account")]
     public int Id {get;set;}
     //properties
     public virtual Account account {get;set;}
  }
  class CurrentAddress : Address
  {
     [ForeignKey("Account")]
     public int Id {get;set;}
     //properties
     public virtual Account account {get;set;}
  }

答案 1 :(得分:1)

实际上最简单的方法是

class Address { 
  // Properties 
}
class Account
{
  //Other Properties
  Public int PermanentAddressId {get;set;}
  Public int CurrentAddressId {get;set;}
  Public Address Permanent { get; set; }
  Public Address Current { get; set; }
}
class Other
{
  //Other Properties
  Public int OtherAddressId {get;set;}
  Public Address OtherAddress { get; set; }
}

class AccountMapping : EntityTypeConfiguration<Account>
{
  Public AccountMapping()
  {
    ToTable("Account");
    //Others like HasKey
    HasRequired(a=>a.ParmanentAddress).WithMany().HasForeignKey(p=>p.PermanentAddressId);
    HasRequired(a=>a.CurrentAddress).WithMany().HasForeignKey(p=>p.CurrentAddressId);
  }
}
class OtherMapping : EntityTypeConfiguration<Other>
{
   public OtherMapping()
   {
     HasRequired(a=>a.OtherAddress).WithMany().HasForeignKey(p=>p.OtherAddressId);
   }
}

答案 2 :(得分:0)

如果要获得一对多关系,则需要定义一个类,该类将包含另一个类的对象列表。 例如,我有两个实体Student和Standard。我希望标准应该包含许多学生。在这种情况下,我使用下一个代码:

public class Student
    {
        public Student() { }

        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public virtual Standard Standard { get; set; }
    }

    public class Standard
    {
        public Standard()
        {
            StudentsList = new List<Student>();
        }
        public int StandardId { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }