[英]Model a database foreign key in c#
I am creating a calendar application. 我正在创建一个日历应用程序。 I have a Appointment table, and a Person table.
我有一个约会表和一个人表。 The 2 are linked by PersonID field in each table.
2通过每个表中的PersonID字段链接。
My question is, should my underlying .Net Appointment object contain a property for the PersonName, and I populate the object from a database view (or stored procedure that joins the tables) or is it more correct to have the Appointment class contain a People class? 我的问题是,我的基础.Net Appointment对象应该包含PersonName的属性,还是从数据库视图(或连接表的存储过程)中填充该对象,还是让Appointment类包含People类更正确? ? If the answer is the latter, what is the best way of populating the Appointment/Person object from the database?
如果答案是后者,那么从数据库填充约会/人员对象的最佳方法是什么?
I am not sure about reading the database. 我不确定要读取数据库。 But the classes could look like:
但是这些类可能看起来像:
public class Person
{
public List<Appointment> Appointments { get; private set; }
...
public Person()
{
Appointments = new List<Appointment>();
}
}
public class Appointment
{
public Person Person { get; set; } // Only if you need this relation from
...
}
And in your model: 在您的模型中:
Persons = new List<Person>();
You should not duplicate properties. 您不应该重复属性。 Once enetity/class should only have properties which are valid for that entity.
一旦enetity / class应该只具有对该实体有效的属性。
If you want to call another table then you should have a property which would return another entity by a specific foreign key. 如果要调用另一个表,则应具有一个将通过特定外键返回另一个实体的属性。
In your case I would have 你的情况我会
public class Person
{
List<Appointment> _appointments;
public List<Appointment> Appointments
{
get
{
if (_appointments == null) _appointments = //LOAD APPOINTMENTS FOR THAT PERSON
return _appointments;
}
}
}
Hope that helps. 希望能有所帮助。
Supposing you're not using an ORM, you may take a look at the DAO pattern: http://en.wikipedia.org/wiki/Data_access_object 假设您没有使用ORM,则可以看一下DAO模式: http : //en.wikipedia.org/wiki/Data_access_object
I would create two DTOs: 我将创建两个DTO:
class Person
{
public int id { get; set; }
public String name { get; set; }
}
class Appointment
{
public int id { get; set; }
public Date when { get; set; }
public Person who { get; set; }
}
And a "full" appointment class: 和一个“完整的”约会类:
class FullAppointment
{
private Person person;
private List<Appointment> appointment;
}
Then a DTO to get data from the DB: 然后使用DTO从数据库获取数据:
class AppointmentDTO
{
public FullAppointment retrieveFromDb(int personId)
{//...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.