与实体框架代码优先的外键关系(EntityData问题)

时间:2015-01-27 19:17:02

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

我有两个实体模型,一个帐户和用户,我在依赖模型(User)中实现外键时遇到困难。在我开发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'实体框架将其解释为'帐户'表,'Id'列。

代码迁移的输出: -

  

User_Account_Source :: Multiplicity在Role中无效   关系'User_Account'中的'User_Account_Source'。因为   依赖角色属性不是关键属性,即上限   依赖角色的多样性必须是'*'。   User_Account_Target_User_Account_Source ::所有属性的类型   在引用约束的依赖角色中必须与之相同   主体角色中的相应属性类型。的类型   实体'User'上的属性'AccountId'与类型不匹配   参照约束中实体'Account'上的属性'Id'   'USER_ACCOUNT'。

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

1 个答案:

答案 0 :(得分:1)

EF理解它的原因是一对多关系而不是一对一是因为你用Id属性组成你的PK,而不是FK.In one- to-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