【问题标题】:My key property is not a Guid type but a custom reference type with a Guid in it我的关键属性不是 Guid 类型,而是包含 Guid 的自定义引用类型
【发布时间】:2015-03-20 14:31:12
【问题描述】:

我有一个域模型,比如在这个类中Contract 我有Id 属性,但这不是简单的Guid 类型,而是ContractId 类型。

public class Contract 
{
    public ContractId Id {get; set; }
}

在我的代码中的其他地方:

public class ContractId 
{
    public Guid Id { get; set; }

    public ContractId(){}
    public ContractId(Guid id){ Id=id; }
}

现在在我的 DbContext 中,我需要说明哪些属性是我的关键属性。

modelBuilder.Entity<Contract>()
.HasKey(k => k.Id)
.ToTable("Contract", "Catalog");

虽然我没有编译时错误,但这会在运行时生气,因为我不能使用 ContractId 作为 Key 属性。然后我考虑指定HasKey(k =&gt; k.Id.Id),因为这是一个有效的Guid,但仍然有问题。我能做什么?

【问题讨论】:

    标签: c# entity-framework domain-driven-design


    【解决方案1】:

    您不能在实体中将Complex Type 用作Key。不幸的是,这是一个limitation of EF。实体的键必须是原始类型,并且必须在同一个类中声明它(它们)。最常见的是,关键成员是 intGUID 类型,尽管任何原始类型都可以用作关键属性。

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多