“一个人”有一个“地址对象”是什么意思?

时间:2015-03-19 23:20:00

标签: asp.net oop composition

在我的最终ASP.NET作业中,我被指示使用代码优先方法并添加以下属性和模型来表示所描述的更改。

1)一个人'有一个'地址对象(已经给出了这个类,但我修改了添加属性)

2)Address对象具有一个类型为string的字符串属性。 (我创建了这个课程)

namespace ContosoUniversity.Models
{
    public class Address
    {
        [Required]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]     {2,4}")]
        public string Email { get; set; }

        [Required]
        [Compare("Email")]
        public string EmailConfirm { get; set; }
    }
}

但现在我不确定他在第一条指令中的含义。我已经研究过组合,继承和抽象类,但仍然不知道我应该做什么?

我怎么想在person类中创建一个Address对象?这究竟意味着什么?这是Person类:

namespace ContosoUniversity.Models
{
    public abstract class Person
    {
        public int ID { get; set; }

        [Required]
        [StringLength(50)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        [Required]
        [StringLength(50, ErrorMessage = "First name cannot be longer than 50     characters.")]
        [Column("FirstName")]
        [Display(Name = "First Name")]
        public string FirstMidName { get; set; }

        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                return LastName + ", " + FirstMidName;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这意味着人与地址之间应该存在一对一的关系。一个人有一个地址。

namespace ContosoUniversity.Models
{
    public abstract class Person
    {
        public int ID { get; set; }

        public Address Address {get; set;}

        [Required]
        [StringLength(50)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
        [Column("FirstName")]
        [Display(Name = "First Name")]
        public string FirstMidName { get; set; }

        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                return LastName + ", " + FirstMidName;
            }
        }
    }
}

现在你可以做这样的事情(假设Person不是抽象类)......

Person person = new Person();
person.Address = new Address();
person.Address.Email = "john.doe@example.com";

如果您的老师说过“一个人可以有多个地址”,您可以做类似的事情(为简洁省略重复的行):

public class Person
{
    public IEnumerable<Address> Addresses {get; set;}

    public Person()
    {
        Addresses = new List<Address>(); //initialize with an empty collection
    }
}

这将允许你这样做......

Person john = new Person();
Address home = new Address(){Email = "john.doe@example.com"}; //create a new address and set its Email property to a value in a single line
Address work = new Address(){Email = "johndoe@work.com"};
john.Addresses.Add(home); //Add the address to the Addresses collection of john
john.Addresses.Add(work);