gpt4 book ai didi

entity-framework - 与 Entity Framework Code First 的外键关系(EntityData 问题)

转载 作者:行者123 更新时间:2023-12-02 07:13:55 24 4
gpt4 key购买 nike

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

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” Entity Framework 将其解释为“Account”表、“Id”列时,就会出现问题。

代码迁移的输出:-

User_Account_Source: : Multiplicity is not valid in Role 'User_Account_Source' in relationship 'User_Account'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. User_Account_Target_User_Account_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'AccountId' on entity 'User' does not match the type of property 'Id' on entity 'Account' in the referential constraint 'User_Account'.

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

最佳答案

EF 之所以理解它是一对多关系而不是一对一关系,是因为您使用 Id 属性编写 PK,这不是 FK。一对一关系,一端必须是主体,另一端必须是依赖主端是第一个插入的端,并且可以在没有从属端的情况下存在。 从属端是必须插入到主体之后的端,因为它具有主体的外键。配置一对一关系时, 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

关于entity-framework - 与 Entity Framework Code First 的外键关系(EntityData 问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28178269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com