【问题标题】:Entity framework optional 1 to 1 relation on both ends实体框架两端可选1对1关系
【发布时间】:2014-01-13 00:18:45
【问题描述】:

我发现的大多数问题都不是我要找的类型。

我有 2 张桌子:

public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid UserId { get; set; }

    public Guid? CustomerId { get; set; }

    [ForeignKey("CustomerId")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CustomerId { get; set; }

    public Guid? UserId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }
}

User 可以存在而不是CustomerCustomer 可以存在而不是User

我尝试了这样的 fluent API:

modelBuilder.Entity<Customer>()
    .HasOptional<User>(c => c.User)
    .WithOptionalDependent(c => c.Customer)
    .Map(c => c.MapKey("UserId"));

但是当我尝试创建迁移时它一直给我这个错误:

Customer_User_Source: : Multiplicity is not valid in Role 'Customer_User_Source' in relationship 'Customer_User'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

更新

我将模型更改为:

public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid UserId { get; set; }

    public virtual Customer Customer { get; set; }
}

public class Customer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CustomerId { get; set; }

    public virtual User User { get; set; }
}

使用流畅的 API:

modelBuilder
    .Entity<Customer>()
    .HasOptional(l => l.User)
    .WithOptionalPrincipal()
    .Map(k => k.MapKey("CustomerId"));

modelBuilder
    .Entity<User>()
    .HasOptional(c => c.Customer)
    .WithOptionalPrincipal()
    .Map(k => k.MapKey("UserId"));

这似乎可行,但有没有办法在模型中定义列,而不必使用MapKey

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-6


    【解决方案1】:

    link 1

    还有link 2

    该链接的问题是我不确定它们是否为问题提供了实际解决方案:因为我不知道它是否为两个表中的外键提供唯一性(正如 link 所建议的那样)。因为没有 EF 唯一约束,您必须手动创建它(在生成器中)

    最后link 解释说,执行 1:* 关系的唯一形式是使用其中一个表的外键作为另一个表的主键。

    祝你好运。

    【讨论】:

    • 感谢第二个链接为我指明了正确的方向,您是否对我的编辑有答案?
    • 我读过是的。我认为这更像是 EF 实施的罪魁祸首。我首先创建了表模型,然后首先从中生成代码。 EF 实际上使它成为 1..* 关系而不是 1..1 关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多