实体框架不将域类中的多个对象添加到数据库

时间:2013-08-30 05:33:06

标签: c# entity-framework asp.net-mvc-4

我是Entity Framework的新手,并试图了解如何在ASP.Net MVC 4应用程序中执行此操作。

我有一个Appointment对象,其中包含一个Customer对象(客户信息)和一个约会的DateTime。我似乎无法弄清楚如何正确存储客户对象。

看看我现在正在做的事情我想我应该存储客户ID,但我不知道如何在以后检索客户信息(我是否使用模型?另一个Domain类“AppointmentDetails”?应该我使用服务层对象?)

   public class Appointment
    {
        public int Id { get; set; }
        public Customer Customer { get; set; }
        public DateTime AppointmentDateTime { get; set; }

        public Appointment()
        {

        }

        public Appointment(Customer customer, DateTime appointmentDateTime)
        {
            Customer = customer;
            AppointmentDateTime = appointmentDateTime;
        }
    }

Customer.cs

   public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }

        public Customer()
        {

        }

        public Customer(string firstName, string lastName, string address, string city, string province, string phone, string email)
        {
            FirstName = firstName;
            LastName = lastName;
            Address = address;
            City = city;
            Province = province;
            Phone = phone;
            Email = email;
        }
    }

1 个答案:

答案 0 :(得分:0)

到目前为止,我一直使用Entity Framework遵循数据库第一种方法,但我相信你的类应该存储这样的东西:

public virtual ICollection<Appointment> Appointment{ get; set; } // which will be used to access your Customer's appointments.

在您的Customer课程中,在您的Appointment课程中,您将拥有:

public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }

你是如何创建这些课程的?如果使用模型设计器,它将生成连接类的必要属性。