实体框架未在域类中向数据库添加多个对象 [英] Entity Framework Not Adding Multiple Objects In A Domain Class To Database

查看:51
本文介绍了实体框架未在域类中向数据库添加多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Entity Framework的新手,并试图了解如何在ASP.Net MVC 4应用程序中做到这一点。

I am new to Entity Framework and trying to understand how to do this in a ASP.Net MVC 4 application.

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

I have an Appointment object that contains a Customer object (customer information) and a DateTime for the appointment. I can't seem to figure out how to store the customer object correctly.

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

Looking at the way I am doing things now I am thinking I should store the customer ID, but I don't know how to retrieve the customer information later (do I use the Model? Another Domain class "AppointmentDetails"? Should I use a service layer object?)

   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

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


推荐答案

所以到目前为止,我一直按照数据库优先方法使用Entity Framework,但是我相信您的类应该存储如下内容:

So far, I've always used Entity Framework following a DB first approach, but I believe your classes should store something like this:

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

在您的客户类中,而在约会类中,您将:

in your Customer class, while in your Appointment class you would have:

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

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

How did you create those classes? If you use the Model designer, it generates the necessary attributes to connect your classes.

这篇关于实体框架未在域类中向数据库添加多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆