【发布时间】:2013-11-27 03:42:06
【问题描述】:
是否可以在已定义的实体属性上创建一对一的关系?我有以下实体:
public class Asset
{
public int AssetId { get; set; }
public int OwningCustomerId { get; set; }
public virtual Customer OwningCustomer { get; set; }
}
public class CustomerAsset
{
public int CustomerId { get; set; } // Primary key 0
public int AssetId { get; set; } // Primary key 1
public int CustomerAssetStatusId { get; set; }
public string Name { get; set; }
public virtual Customer Customer { get; set; }
public virtual Asset Asset { get; set; }
}
CustomerAsset 代表资产的各种所有权状态。虽然同一个 AssetId 可以在此表中多次存在,但只有一个实例 CustomerAssetStatusId = 1。为了快速访问资产的当前所有者,我还在 Asset 表中维护了 OwningCustomerId。
我想要一个从 Asset 到 CustomerAsset 的导航属性,称为 OwningCustomerAsset。这是一对一的关系。不幸的是,我不知道如何定义它,因为外键字段已经在 Asset.xml 中定义。通常,我会在 Asset 上创建这样的关系:
HasRequired(e => e.OwningCustomerAsset).WithRequiredDependent().Map(m => m.MapKey("OwningCustomerId", "AssetId"));
当然,这会导致以下错误:“类型中的每个属性名称都必须是唯一的。属性名称‘OwningCustomerId’已被定义。”
我如何告诉 EF OwningCustomerId/AssetId 是 CustomerAsset 的外键?
【问题讨论】:
标签: c# entity-framework ef-code-first