【问题标题】:Foreign Key Relationships with Entity Framework Code First (EntityData Issue)与实体框架代码优先的外键关系(EntityData 问题)
【发布时间】:2015-03-26 12:39:40
【问题描述】:

我有两个实体模型,一个帐户和一个用户,我在依赖模型(用户)中实现外键时遇到了困难。在开发 Azure 移动服务应用程序时,我需要使用默认提供“Id”键字段的实体数据接口。

public class Account : EntityData
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AccountId { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string EmailAddress { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string SecurityQuestion { get; set; }
    [Required]
    public string SecurityAnswer { get; set; }
    [Required]
    public bool IsBusiness { get; set; }

    public virtual User User { get; set; }
    public virtual Business Business { get; set; }
}

public class User : EntityData
{
    [Key, Column(Order=1)]
    public virtual string Id { get; set; }
    [Key, Column(Order=2), ForeignKey("Account")]
    public int AccountId { get; set; }
    public int UserId { get; set; }
    [Required]
    public string Forename { get; set; }
    [Required]
    public string Surname { get; set; }

    public virtual Account Account { get; set; }
}

当我指定要查找“AccountId”实体框架将其解释为“Account”表、“Id”列时,会出现我的问题。

代码迁移的输出:-

User_Account_Source: : 多重性在角色中无效 关系“User_Account”中的“User_Account_Source”。因为 Dependent Role 属性不是关键属性,上限 从属角色的多重性必须是“*”。 User_Account_Target_User_Account_Source: : 所有属性的类型 在引用约束的 Dependent Role 中必须与 Principal Role 中的相应属性类型。的类型 实体“用户”上的属性“帐户 ID”与 引用约束中实体“帐户”的属性“Id” 'User_Account'。

任何见解都将受到高度赞赏!

【问题讨论】:

  • 为什么User 有一个复合主键? Id 还不够吗?
  • 我不想使用 EntityData 生成的 GUID Id 字段,而是使用我自己的(UserId 和 AccountId)。尝试将我的 Key 设为主键,但由于 EntityData Id 键,我必须订购它

标签: entity-framework azure ef-code-first foreign-keys ado.net-entity-data-model


【解决方案1】:

EF 理解它是一对多关系而不是一对一的原因是因为您正在使用 Id 属性组成您的 PK,这不是 FK。在 一对一one 关系 一端必须是主要的,而另一端必须是从属主端是最先插入的端,可以在没有依赖端的情况下存在。 从属端是必须插入到主体之后的一端,因为它具有主体的外键。在配置一对一关系时,Entity Framework 要求依赖的主键也是外键,否则 EF 不会将其视为一对一关系。

public class Account
{
   [Key]
   public int  Id  { get; set; }

   public virtual User User{ get; set; }
}

public class User
{
   [Key, ForeignKey("Account")]
   public int  AccountId { get; set; }

   public virtual Account Account{ get; set; } 
}

如果你考虑一下,这是有道理的,否则可能会出现以下记录:

Accounts
Id 
11111111
22222222

Users
Id       AccountId
12rr      11111111
22tt      11111111

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多