【发布时间】:2011-12-11 10:09:29
【问题描述】:
我有 4 个课程。供应商、客户、员工和地址。前 3 种类型中的任何一种都可以有“n”个地址。所以类看起来像这样;
class Address
{
int Id { get; set; }
int ParentId { get; set; } // NOTE: This is the FK.
IAggregateRoot Parent { get; set; } // EXAMPLE: Supplier, Customer, Employee ..
// rest of the address fields.
}
class Supplier : IAggregateRoot
{
int Id { get; set; }
virtual List<Address> Addresses { get; set; }
// rest of the supplier details.
AddAddress(Address address)
{
address.Parent = this;
address.ParentId = this.Id;
Addresses.Add(address);
}
}
class Customer : IAggregateRoot
{
int Id { get; set; }
virtual List<Address> Addresses { get; set; }
// rest of the customer details.
AddAddress(Address address)
{
address.Parent = this;
address.ParentId = this.Id;
Addresses.Add(address);
}
}
class Employee : IAggregateRoot
{
int Id { get; set; }
virtual List<Address> Addresses { get; set; }
// rest of the employee details.
AddAddress(Address address)
{
address.Parent = this;
address.ParentId = this.Id;
Addresses.Add(address);
}
}
如何编写地址的父属性的映射?或者更好的方法/设计来完成这种场景?
【问题讨论】:
-
您需要父母提供地址吗?你多久搜索一次那个方向?我会在数据库中将其表示为具有地址 ID 的父母。然后对不同类型的父母进行三个单独的(可能是手动的)查询。否则,您必须使用可能具有地址的那些类型的继承层次结构。它们在问题域中是否以任何方式在逻辑上相关,或者这只是一个代码问题?
-
@MerlynMorgan-Graham 我不希望每个 Parent 类型都有很多 Address 类。因此,我已将我的类图标准化为具有许多父类型的 Address 类。如果我在 Old-School SQL 存储过程和 IDataReader 方法中执行此操作,我可以管理它,但我无法弄清楚我必须如何为此编写流利的配置。不,我不想从地址查询/导航到父级。
-
不,您的地址类没有很多父类型。它有 1 个父类型—— IAggregateRoot。 EF 会认为这是一个 1..N 关系,其中每个地址只有 1 个父级。
标签: c# entity-framework orm ef-code-first code-first